1. 程式人生 > >ALinq 使用教程(四)驗證實體類

ALinq 使用教程(四)驗證實體類

新增 Validate Attribute 到屬性

選取 Product 類中的 PropertyName 屬性,在屬性視窗中,選擇 Attributes 項,然後點選旁邊的按鈕。在彈出的對話方塊中,雙擊左邊 Attribute List 中的 RequiredAttribute 項,將其新增到右邊。在屬性視窗中,將 AllowEmptyString 設為 False ,點選 OK 按鈕儲存。

實現擴充套件方法

在設計器中,滑鼠右鍵點選 Product 類,在彈出的選單中,選擇 ViewCode (或者按 F7 快捷鍵)。

匯入名稱空間

using System;
using
System.ComponentModel.DataAnnotations;
using System.Linq;

在 Prodcut 類中,新增下面的方法用於對實體類的屬性進行驗證。

程式碼 partialvoid OnValidate(ALinq.ChangeAction action)
{
var propertyInfos
=this.GetType().GetProperties();
foreach (var propertyInfo in propertyInfos)
{
var customeAttributes
= propertyInfo.GetCustomAttributes(
true)
.Where(o
=> o is ValidationAttribute)
.Cast
<ValidationAttribute>();

foreach (var attribute in customeAttributes)
{
attribute.Validate(propertyInfo.GetValue(
this, null), propertyInfo.Name);
}
}
}

在 Program.cs 檔案中,新增下面的程式碼:

程式碼 staticvoid Main(string[] args)
{
var dc
=new NorthwindDataContext()
{
Log
= Console.Out
};

var product
=new Product { Productname ="" };
dc.Products.InsertOnSubmit(product);
dc.SubmitChanges();
}

按 Ctrl + F5 執行,從圖中可以發現,丟擲了一個異常,那是因為 ProductName 屬性驗證失敗了。

關於更多驗證方面的內容,請參考:

或者 Google : Linq to SQL validate