The reflection and feature technologies provided by .net framework can be used to check data repeatability to decide whether to write a certain piece of data to the database table.
When an entity writes a piece of data to the database, many times it is necessary to check whether the data is a duplicate, such as a new person, assuming The ID number cannot be repeated. If the newly created personnel ID number is duplicated with one or more entries in the personnel table, a prompt or other means need to be given, such as updating or deleting.
In this demand scenario, you can use the features and reflection technology provided by .net framework to solve such needs. The specific process,
Secondly, reference the newly written feature class in the entity class to construct its unique identifier (one or more attribute combinations);
Finally, When checking data repeatability, use the method provided by Attribute to obtain the unique identification attribute (one or more) of each entity class.
Attribute[] GetCustomAttributes(modeltype, inherit);
public class KeyFieldAttribute:Attribute { private static List<string> keyfields = new List<string>(); /// <summary> /// 构造关键属性 /// </summary> /// <param name="fields"></param> public KeyFieldAttribute(params string[] fields) { foreach (string kf in fields) { if (!keyfields.Contains(kf)) keyfields.Add(kf); } } public static List<string> KeyFields { get { return keyfields; } } }
[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.GetCustomAttributes(typeof(Person), true); List<string> fields = KeyFieldAttribute.KeyFields; //获取到Person实体的唯一标识属性ID KeyFieldAttribute.GetCustomAttributes(typeof(Role), true); var fields = KeyFieldAttribute.KeyFields;//Role实体唯一属性,2个属性组合:RoleGroupID,RoleCode
/// <summary>/// 检索应用于类型的成员的自定义特性的数组。 /// </summary>/// <param name="modeltype">要搜索的自定义特性的类型</param> ///<param name="inherit">是否搜索成员的祖先</param> /// <returns>自定义特性的数组</returns>Attribute[] GetCustomAttributes(modeltype, inherit);