• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

.NET框架-应用特性和反射检查数据唯一性的示例代码

c# 搞代码 4年前 (2022-01-09) 21次浏览 已收录 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);            }        }        publi<strong style="color:transparent">来源gaodai#ma#com搞@代~码$网</strong>c 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);

以上就是.NET框架-应用特性和反射检查数据唯一性的示例代码的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:.NET框架-应用特性和反射检查数据唯一性的示例代码
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址