2011-05-13 91 views
0

我正在使用Castle ActiveRecord重组我们的数据库访问权限。我已经通过博客/后期示例来了解事情的完成情况,但是我有一个关于HasMany属性的基本问题。请看下面的例子:Castle ActiveRecord HasMany属性

班级博客:

[ActiveRecord] 
public class Blog : ActiveRecordBase 
{ 
    private int id; 
    private IList posts = new ArrayList(); 

    public Blog() 
    { 
    } 

    [PrimaryKey] 
    public int Id 
    { 
     get { return id; } 
     set { id = value; } 
    } 

    [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid", 
     Inverse=true, Cascade=ManyRelationCascadeEnum.AllDeleteOrphan)] 
    public IList Posts 
    { 
     get { return posts; } 
     set { posts = value; } 
    } 
} 

类岗位:

[ActiveRecord] 
public class Post : ActiveRecordBase 
{ 
    private int id; 
    private String contents; 
    private Blog blog; 

    public Post() 
    { 
    } 

    [PrimaryKey] 
    public int Id 
    { 
     get { return id; } 
     set { id = value; } 
    } 

    [Property(ColumnType="StringClob")] 
    public String Contents 
    { 
     get { return contents; } 
     set { contents = value; } 
    } 

    [BelongsTo("blogid")] 
    public Blog Blog 
    { 
     get { return blog; } 
     set { blog = value; } 
    } 
} 

现在当我创建一个博客,并添加一些职位,以这个博客,为什么是Blog.Posts集合不会自动更新?这是代码:

using (new SessionScope()) 
{ 
    Blog b = new Blog(); 
    b.Save(); 

    Post p = new Post(); 
    p.Blog = b; 
    p.Save(); 

    //Here, b.Posts is empty, but shouldn't it contain a reference to p? 
} 

可以做些什么来防止这种行为?我必须手动将帖子添加到收藏夹吗?这里有什么最佳实践?

TIA

回答

2

您应该将后只需添加到

using (new SessionScope()) 
{ 
    Blog b = new Blog(); 

    Post p = new Post(); 
    p.Blog = b; 

    b.Posts.Add(p); 

    b.Save(); 
} 

的帖子收集不,除非你从数据库刷新你的博客的对象不会被自动更新,您的博客对象的帖子财产。