本文主要包括以下內容:
1、有效性驗證
2、交易處理
一、Validation(驗證)
ActiveRecord內建了資料驗證的功能,具體實現是放在實體類的Attribute特性裡的,這個時候我們的實體類需要繼承ActiveRecordValidationBase 這個類.目前支援以下幾種驗證:
1、ValidateEmail 驗證是否為有效Email地址
2、ValidateIsUnique 驗證是否唯一
3、ValidateRegExp 驗證是否匹配輸入的Regex
4、ValidateNotEmpty 驗證是否為空白
5、ValidateConfirmation 需要先判斷另外一個欄位是否通過驗證,以確定它本身的驗證是否通過
當然AR也支援自訂的驗證方法,詳細說明請參考: http://terrylee.cnblogs.com/archive/2006/04/13/374173.html
ActiveRecordValidationBase 這個類還提供了兩個方法/屬性,以協助我們獲得驗證是否通過和錯誤資訊.如下:
1.IsValid(),返回驗證是否通過,Bool型
2.ValidationErrorMessages,屬性,返回錯誤資訊.
[ActiveRecord("companies")]public class Company : Castle.ActiveRecord.ActiveRecordValidationBase{private int _id;private int _pid;private string _cname;private string _type;public Company(){}public Company(string name){this._cname = name;}[PrimaryKey]public int Id{get{return _id;}set{_id = value;}}[Property,ValidateNotEmpty("上級機構不可為空!")]public int Pid{get{return _pid;}set{_pid = value;}}[Property,ValidateNotEmpty("機構名稱不可為空!")]public string Cname{get{return _cname;}set{_cname = value;}}[Property]public string Type{get{return _type;}set{_type = value;}} }
public void AddCompany(){using (TransactionScope trans = new TransactionScope()){Company com = new Company();com.Pid = 0;com.Create();try{//判斷驗證是否通過 if(!com.IsValid()){//獲得錯誤資訊string[] errors = com.ValidationErrorMessages;string esg = string.Empty;for(int i=0;i<errors.Length;i++){esg += errors[i].ToString() + ",";}throw new ApplicationException(esg);}trans.VoteCommit();}catch(Exception e){trans.VoteRollBack();throw new ApplicationException(e.Message);}}
二、交易處理
AR的交易處理非常的簡單,如下:
public void UseTransaction(){using (TransactionScope trans = new TransactionScope ()){try{People p = new People();p.Name = "TransactionExample";p.Create();trans.VoteCommit();}catch(Exception){trans.VoteRollBack();throw;}}}
另外AR還提供一種交易處理的方法,稱之為嵌套交易處理(Nested transactions ),使用方法如下:
public void UserNestedTransaction(){using (TransactionScope t = new TransactionScope()){Company c = new Company();using(TransactionScope t1 = new TransactionScope(TransactionMode.Inherits)){c.Pid = 0;c.Cname = "Nested";c.Type = "T";c.Save();t1.VoteCommit();}using(TransactionScope t2 = new TransactionScope(TransactionMode.Inherits)){People p = new People();p.Name = "SHY520";try{p.Save();}catch(Exception){t2.VoteRollBack();}}}}
因為工作的原因,AR我暫時就說這麼多了,待會再把部落格園關於這方面的文章整理一下,同時還是很希望和對AR有興趣的人多多交流。
寫的不對的地方,請指正,謝謝。
Email:pwei013@163.com