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

时间:2022-03-09 22:40:08

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

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

     public class Property : System.Attribute
{
public string Value { get; set; } public Property(string Value)
{
this.Value = Value;
}
}

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

         [Property("PrimaryKey")]
public long APId
{
set{ _apid=value;}
get{return _apid;}
}

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

        foreach (PropertyInfo p in pros)
   {
//获取自定义属性
object[] objArray = p.GetCustomAttributes(false);
//判断是否已获取到自定义属性Property,如果已获取objArray.length>0,在此处用来过滤主键,
            拼接字符串不要把主键拼接进去在Id旁边添加属性名称“PrimaryKey”
if (objArray.Length <= )
{
strSql.Append(p.Name);
if (i < pros.Length - )
strSql.Append(",");
i++;
} }