Castle ActiveRecord HasMany属性

时间:2011-05-13 11:51:39

标签: nhibernate castle-activerecord

我正在使用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

1 个答案:

答案 0 :(得分:2)

您只需将帖子添加到博客对象的帖子属性

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

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

    b.Posts.Add(p);

    b.Save();
}

除非您从数据库重新加载博客对象,否则Posts集合不会自动更新。