C#在数据层过滤属性中的主键

C#使用泛型+反射做为数据层时,一个很都头疼的问题,如何让C#属性在程序里识别出哪个属性是主键,在拼接SQL时,不能把主键拼接到SQL语句里。

这个需要自定义一个属性。新建一个类文件,命名为ProsperTest.cs

1     public class Property : System.Attribute
2     {
3         public string Value { get; set; }
4 
5         public Property(string Value)
6         {
7             this.Value = Value;
8         }
9     }

在MODEL层新建一个跟表对应的属性AssetPurchase.cs类

1         [Property("PrimaryKey")]
2         public long APId
3         {
4             set{ _apid=value;}
5             get{return _apid;}
6         }        

在数据层代码中编写拼接SQL字符串代码

 1        foreach (PropertyInfo p in pros)
 2          {
 3                  //获取自定义属性
 4                 object[] objArray = p.GetCustomAttributes(false);
 5                 //判断是否已获取到自定义属性Property,如果已获取objArray.length>0,在此处用来过滤主键,
            拼接字符串不要把主键拼接进去在Id旁边添加属性名称“PrimaryKey”
6 if (objArray.Length <= 0) 7 { 8 strSql.Append(p.Name); 9 if (i < pros.Length - 1) 10 strSql.Append(","); 11 i++; 12 } 13 14 }
原文地址:https://www.cnblogs.com/luyuwei/p/5163309.html