tangxu
2022-10-08 a36faf95b4bee06626f33a82448f93e364b29ec5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace IStation.DataProvider
{
    /// <summary>
    /// 实体辅助类
    /// </summary>
    public class EntityHelper
    {
        //默认主键名称
        private static readonly string _defaultPrimaryKey = "ID";
 
        /// <summary>
        /// 获取表名称
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string GetTableName<T>()
        {
            var objType = typeof(T);
            var attrs = objType.GetCustomAttributes(typeof(TableAttribute), true);
            if (attrs != null && attrs.Count() > 0)
                return (attrs[0] as TableAttribute).Name;
            return objType.Name;
        }
 
        /// <summary>
        /// 获取主键属性信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string GetPrimaryKey<T>()
        {
            var objType = typeof(T);
            var pros = objType.GetProperties();
            var keyPro = pros.FirstOrDefault(x => x.GetCustomAttribute(typeof(KeyAttribute)) != null);
            if (keyPro != null)
                return keyPro.Name;
            var explicitKeyPro = pros.FirstOrDefault(x => x.GetCustomAttribute(typeof(ExplicitKeyAttribute)) != null);
            if (explicitKeyPro != null)
                return explicitKeyPro.Name;
            return _defaultPrimaryKey;
        }
 
 
    }
}