HasMany--表示一对多的关系
Posts 的blogid是blogs表的外键,可以在blog类中设置HasMany属性,使blog类有一系列的Posts
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"),
Inverse=true, Cascade=ManyRelationCascadeEnum.AllDeleteOrphan)]
public IList Posts
{
get { return posts; }
set { posts = value; }
}
}
注意:如果另一边有关联的类(Post类)有BelongsTo关联blog类,可以省略Table和ColumnKey 属性
使用示例:
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();