使用DataAnnotations实现数据验证

来源:互联网 发布:淘宝旺旺卖家版手机版 编辑:程序博客网 时间:2024/05/22 16:38

在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 { getset; }

}

public class PriceAttribute : ValidationAttribute

 {

       public double MinPrice { getset; }  

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

   } 

  } 

0 0