浅谈DataAnnotations

在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 中无对应项

posted @ 2012-04-25 14:53  蓝雨.Berners  阅读(10462)  评论(0编辑  收藏  举报