Ralf
Ralf

Reputation: 1

Castle ActiveRecord HasMany attribute

I'm using Castle ActiveRecord reorganize our database access. I've worked through the blog/post example to get a feeling on how things are done, but I've one essential question regarding the HasMany attribute. See the following example:

Class Blog:

[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; }
    }
}

Class Post:

[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; }
    }
}

When I now create a blog and add some posts to this blog, why is the Blog.Posts collection not automatically updated? This is the code:

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?
}

What can be done to prevent this behaviour? Do I have to add the post to the collection manually? What are the best practices here?

TIA

Upvotes: 0

Views: 1250

Answers (1)

mathieu
mathieu

Reputation: 31202

You should just add your post to the Posts property of your blog object

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

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

    b.Posts.Add(p);

    b.Save();
}

The Posts collection doesn't get updated automatically, unless you reload your blog object from database.

Upvotes: 2

Related Questions