.NET框架-应用特性和反射检查数据唯一性

作者:vuefine
文献: msdn library
平台:.NET 2.0+


反射和特性


 .net framework提供的反射和特性技术,可以用来检查数据重复性,以决定是否向数据库表中写入某条数据。
 

需求


  某个实体向数据库写入一条数据时,很多时候,需要检查这条数据是不是一条重复数据,比如新建的人员,假定ID号码不能重复,此时新建的这个人员ID号与人员表中的一条或多条重复了,此时需要给出提示或采取其他手段,比如更新,或删除等。

方法


  在这种需求场景下,可以利用.net framework提供的特性与反射技术,解决此类需求。具体过程,

  其次,在实体类中引用刚写好的特性类构造出其唯一标识(一个或多个属性组合);
  
  最后,检查数据重复性时,运用Attribute提供的方法,获取每个实体类的唯一性标识属性(一个或多个)。
  
  Attribute[] GetCustomAttributes(modeltype, inherit);

KeyFieldAttribute 特性类

     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; }
        }
    }

实体类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<string> fields = KeyFieldAttribute.KeyFields; //获取到Person实体的唯一标识属性ID

            KeyFieldAttribute.GetCustomAttributes(typeof(Role), true);
            var fields = KeyFieldAttribute.KeyFields;//Role实体唯一属性,2个属性组合:RoleGroupID,RoleCode

  利用特性返回的关键属性组合,在数据库中查询数据,如果能查到至少一条记录,则按照一定的逻辑处理; 如果不能,则可以直接写入新数据。Attribute类中提供的方法说明:

/// <summary>
/// 检索应用于类型的成员的自定义特性的数组。
/// </summary>
/// <param name="modeltype">要搜索的自定义特性的类型</param>
///<param name="inherit">是否搜索成员的祖先</param>
/// <returns>自定义特性的数组</returns>
Attribute[] GetCustomAttributes(modeltype, inherit);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值