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 the 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; }//角色名称 }
Pay attention to the attribute extension class. Here, the suffix Attribute in KeyFieldAttribute can be omitted, so KeyField is an abbreviation, equivalent to KeyFieldAttribute.
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
Use the key attribute combination returned by the feature to query data in the database. If at least one record can be found, follow certain logic processing; if not, new data can be written directly. Method description provided in Attribute class:
/// <summary>/// 检索应用于类型的成员的自定义特性的数组。/// </summary> /// <param name="modeltype">要搜索的自定义特性的类型</param> ///<param name="inherit">是否搜索成员的祖先</param> /// <returns>自定义特性的数组</returns>Attribute[] GetCustomAttributes(modeltype, inherit);
The above is the detailed content of .NET Framework - Sample code for applying attributes and reflection to check data uniqueness. For more information, please follow other related articles on the PHP Chinese website!