您的位置:首页 > 其它

Castle ActiveRecord学习实践(7)级联

2012-10-30 00:16 369 查看
本章来看看CastleActiveRecord中的级联(cascade)操作

还是以post和comment为例

post.cs修改为

[ActiveRecord("Posts")]

[code]publicclassPost:ActiveRecordBase<Post>
{

[PrimaryKey("PostId")]

publicintId{get;set;}


[Property]

publicstringSubject{get;set;}


[Property]

publicstringText{get;set;}


[Property]

publicDateTimeDateAdded{get;set;}


[BelongsTo("CategoryId")]

publicCategoryCategory{get;set;}


[HasMany(Lazy=true,Cascade=ManyRelationCascadeEnum.AllDeleteOrphan,Inverse=true)]

publicIList<Comment>Comments{get;set;}


[HasAndBelongsToMany(typeof(Tag),Table="TagPost",ColumnKey="PostId",ColumnRef="TagId")]

publicIList<Tag>Tag{get;set;}


}

[/code]

HasMany特性添加Cascade

枚举属性

枚举
ManyRelationCascadeEnumNone不做级联操作
All增删改都做级联操作
AllDeleteOrphan都做级联操作,并且删除孤儿数据。即删除没有对应Post的Comment对象
SaveUpdate在增加和更新的时候做级联操作
Delete在删除的时候做级联操作
1、级联添加

创建一个post,并添加多个comment

//创建post

[code]Postpost=newPost();
post.DateAdded=DateTime.Now;

post.Subject="castleactiverecord7";

post.Text="content";

List<int>list=newList<int>();

list.Add(1);

list.Add(2);

post.Category=Category.Find(5);

post.Tag=Tag.FindAll();

using(TransactionScopetran=newTransactionScope())

{

try

{

post.Create();

for(inti=0;i<10;i++)

{

//创建comment

Commentcomment=newComment();

comment.Author="hzd"+i;

comment.DateAdded=DateTime.Now;

comment.Text="comment"+i+"content!";

comment.Post=post;

comment.Save();

}

tran.VoteCommit();


}

catch

{

tran.VoteRollBack();

}

}

[/code]

2、级联更新

为已经存在的post添加comment


Postpost=newPost();

[code]post=Post.Find(8);
using(TransactionScopetran=newTransactionScope())

{

try

{

for(inti=0;i<5;i++)

{

//创建comment

Commentcomment=newComment();

comment.Author="hzd-"+i;

comment.DateAdded=DateTime.Now;

comment.Text="comment"+i+"content!";

comment.Post=post;

comment.Save();

}

post.Text="castleactiverecordCascade";

post.Update();

tran.VoteCommit();


}

catch

{

tran.VoteRollBack();

}

}


[/code]

3、级联删除

删除一个post



Postpost=newPost();

[code]post=Post.Find(1);
post.Delete();

[/code]

删除一个post的一个comment


using(newSessionScope())

[code]{
Postpost=newPost();

post=Post.Find(8);

intcount=post.Comments.Count;

post.Comments.RemoveAt(0);

post.Update();

}

[/code]

特别注意


[HasMany(Lazy=true,Cascade=ManyRelationCascadeEnum.AllDeleteOrphan,Inverse=true)]

[code]publicIList<Comment>Comments{get;set;}
[/code]

设置One-To-Many中One方(本文中的post)HasManyAttribute的Inverse属性为true

Inverse属性指定了双向关联中的所有者,它的默认值为false。

Inverse为true是,关联关系的维护者为主表(即posts表)。

为false时,关联关系的维护者为子表(即comments表),如果子表设置了外键不为null,会出现

不能将值NULL插入列'外键列'

的错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: