Home

Castle Stronghold

HasMany

An one-to-many relation can be mapped using the HasManyAttribute.

Consider the following table script:


CREATE TABLE Blogs 
(
    [id] [int] IDENTITY (1, 1) NOT NULL,
    [name] [varchar] (50) NULL
) ON [PRIMARY]

CREATE TABLE Posts 
(
    [id] [int] IDENTITY (1, 1) NOT NULL,
    [title] [varchar] (50) NULL,
    [contents] [text] NULL,
    [blogid] [int] NULL
) ON [PRIMARY]

The blogid on Posts is clear a foreign key to the Blogs table. You can make the Blog class have a set of Posts using the HasManyAttribute:


using Castle.ActiveRecord;

[ActiveRecord("blogs")]
public class Blog : ActiveRecordBase
{
    private int id;
    private string name;
    private IList posts = new ArrayList();
    
    [PrimaryKey]
    public int Id
    {
        get { return id; }
        set { id = value; }
    }

    [Property]
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    
    [HasMany(typeof(Post), Table="Posts", ColumnKey="blogid")]
    public IList Posts
    {
        get { return posts; }
        set { posts = value; }
    }
}
Quick Note

If the other side of the relation (the Post class) had a BelongsTo relation to the Blog class, the you could omit the Table and ColumnKey properties.

Now we can use the newly added relation:


Blog blog = new Blog();
blog.Name = "hammett's blog";
blog.Create();

Post post = new Post();
post.Title = "First post";
post.Contents = "Hello world";
post.Create();

blog.Posts.Add(post);
blog.Update();

By default this kind of relation is writable. You can control the behavior using the Cascade property on HasManyAttribute. You can also turn off the writable behavior by saying that the relation is only controlled by the other side. You can do this using the Inverse property. For example:


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

More information on the attribute can be found at Attributes article. For an explanation of the Inverse concept, please refer to this article at nhprof.com.

Google
Search WWW Search castleproject.org