您的位置:首页 > 其它

使用DataAnnotations实现数据验证

2015-06-02 09:22 169 查看
在Entity Framworik(Module)中有两种配置:一种 DataAnnotaions(注释)与Fluent API.这些根据个人喜欢来使用,DataAnnotaions 配置相对简单些,Fluent API可以配置些复杂的功能。今天我们来简单说说DAtaAnnotaions 的属性--命名空间:System.ComponentModel.DataAnnotations四个属性:
属性名称描述
Required标识该属性为必需参数,不能为空
StringLength标识该字符串有长度限制,可以限制最小或最大长度
Range标识该属性值范围,通常被用在数值型和日期型
RegularExpression标识该属性将根据提供的正则表达式进行对比验证
CustomValidation标识该属性将按照用户提供的自定义验证方法,进行数值验证
Validations---这个是所有验证属性的基类(后面我们会用到)例如:Public class Test{ [Required(ErrorMessage="")] Public string Title{get;set;} [StringLength(6, ErrorMessage="xx")] Public string Name{get; set;} Public string Email{get; set;} [Price(MinPrice = 1.99)] //自定义验证 public double Price { get; set; }}public class PriceAttribute : ValidationAttribute { public double MinPrice { get; set; } public override bool IsValid(object value) { if (value == null) { return true; } var price = (double)value; if (price < MinPrice) { return false; } double cents = price - Math.Truncate(price); if(cents < 0.99 || cents >= 0.995) { return false; } return true; } } 注意:MaxLength在数据库有对应的含义,而MinLength并不有.MinLength将会用于EF框架的验证,并不会影响数据库. MinLength只能通过Data Annotations来进行配置,在Fluent API 中无对应项
此外,在使用了实体框架EF自动生成了类后,如果要使用DataAnnotations中的特性类,可以使用在分部类中添加内部元数据类型的方法来实现(假设EF已经自动创建了分部User类): 新建==>类,命名为User,然后改成分部类:为类添加MetadataType特性,并在类中添加一个内部类 //注意:两个User类必须在同一个命名空间中!!! using System.ComponentModel.DataAnnotations;namespace Test{ [MetadataType(typeof(UserMD))] //类名UserMD随便起,但需要和后面一致 public particial class User { public class UserMD { [Required] public int UserId{set; get;} [Range(1,200,ErrorMessage="年龄超出范围")] public int Age(set; get;} } } }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: