数据验证(自定义特性)
这几天在了解ef,看了几天云里雾里(我太菜了),但在vs2010中使用ef时我觉得有些东西还是很有意思的。自己便想到分装一个逻辑层的数据验证类
1.自定义特性
[AttributeUsage(AttributeTargets.Property)] public class CheckAttributes:Attribute { // 摘要: // 初始化类的新实例。 public CheckAttributes(bool iskey, bool isnull) { this.EntityKeyProperty = iskey; this.IsNullable = isnull; } // 摘要: // 获取或设置一个值,该值指示属性是否为实体键的一部分。 // // 返回结果: // 一个值,该值指示属性是否为实体键的一部分。 public bool EntityKeyProperty { get; set; } // // 摘要: // 获取或设置一个值,该值指示属性是否可以具有 null 值。 // // 返回结果: // 一个值,该值指示属性是否可以具有 null 值。 public bool IsNullable { get; set; } }
2.创建带有自定义特性的实体类
public class Ent { public static Ent Create_Ent(Int32 id, String contex) { Ent ent=new Ent(); ent.Id = id; ent.Contex = contex; return ent; } private Int32 _id; [CheckAttributes(true,false)] //是实体键,不可为空 [DataMember] public Int32 Id { get { return _id; } set { this._id = value; } } private String _contex; [CheckAttributes(false,false)] // 不是实体键,不可为空 [DataMember] public String Contex { get { return _contex; } set { this._contex = value; } } }