反射和特性
.net framework提供的反射和特性技术,可以用来检查数据重复性,以决定是否向数据库表中写入某条数据。
需求
某个实体向数据库写入一条数据时,很多时候,需要检查这条数据是不是一条重复数据,比如新建的人员,假定id号码不能重复,此时新建的这个人员id号与人员表中的一条或多条重复了,此时需要给出提示或采取其他手段,比如更新,或删除等。
方法
在这种需求场景下,可以利用.net framework提供的特性与反射技术,解决此类需求。具体过程,
其次,在实体类中引用刚写好的特性类构造出其唯一标识(一个或多个属性组合);
最后,检查数据重复性时,运用Attribute提供的方法,获取每个实体类的唯一性标识属性(一个或多个)。
Attribute[] GetCustomAttributes(modeltype, inherit);
KeyFieldAttribute 特性类
- public class KeyFieldAttribute:Attribute { private static List keyfields = new List(); ///
/// 构造关键属性 /// /// public KeyFieldAttribute(params string[] fields) { foreach (string kf in fields) { if (!keyfields.Contains(kf)) keyfields.Add(kf); } } public static List KeyFields { get { return keyfields; } } }
登录后复制
实体类Model
- [KeyField("ID")]public class Person{ public int ID {get;set;} //人员ID public string Name {get;set;}//人员名称 public DateTime BirthDate {get;set;} //出生年月日} [KeyField("RoleGroupID","RoleCode")] public class Role { public int RoleGroupID { get; set; } //角色组别ID public string RoleCode { get; set; } //角色编号 public string RoleName { get; set; }//角色名称 }
登录后复制
注意特性扩展类,此处是KeyFieldAttribute中的后缀Attribute是可以省略的,因此KeyField是简写,相当于KeyFieldAttribute。
运用特性类:
- KeyFieldAttribute.GetCustomAttributes(typeof(Person), true); List fields = KeyFieldAttribute.KeyFields; //获取到Person实体的唯一标识属性ID KeyFieldAttribute.GetCustomAttributes(typeof(Role), true); var fields = KeyFieldAttribute.KeyFields;//Role实体唯一属性,2个属性组合:RoleGroupID,RoleCode
登录后复制
利用特性返回的关键属性组合,在数据库中查询数据,如果能查到至少一条记录,则按照一定的逻辑处理; 如果不能,则可以直接写入新数据。Attribute类中提供的方法说明:
////// 检索应用于类型的成员的自定义特性的数组。/// /// 要搜索的自定义特性的类型///是否搜索成员的祖先/// 自定义特性的数组Attribute[] GetCustomAttributes(modeltype, inherit);
登录后复制
以上就是.NET框架-应用特性和反射检查数据唯一性的示例代码的详细内容,更多请关注【创想鸟】其它相关文章!