在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 中無對應項