本文主要包括以下内容:
1、有效性验证
2、事务处理
一、Validation(验证)
ActiveRecord自带了数据验证的功能,具体实现是放在实体类的Attribute特性里的,这个时候我们的实体类需要继承ActiveRecordValidationBase 这个类.目前支持以下几种验证:
1、ValidateEmail 验证是否为有效的Email地址
2、ValidateIsUnique 验证是否唯一
3、ValidateRegExp 验证是否匹配输入的正则表达式
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