Castle ActiveRecord学习实践(6)延迟加载
前言
前面的几章介绍了Castle ActiveRecord如何处理关系映射,以及面向对象中的继承。在ActiveRecord中把数据库表之间的关联关系采用对象间的聚合关系来表现,这会带来一个问题,查询post的时候会连带着查询comment。本章的内容就是处理这个问题
启用延迟加载
HasMany特性Lazy设置为true
1: [ActiveRecord("Posts")]
2: public class Post : ActiveRecordBase<Post>
3: {
4: [PrimaryKey("PostId")]
5: public int Id { get; set; }
6:
7: [Property]
8: public string Subject { get; set; }
9:
10: [Property]
11: public string Text { get; set; }
12:
13: [Property]
14: public DateTime DateAdded { get; set; }
15:
16: [BelongsTo("CategoryId")]
17: public Category Category { get; set; }
18:
19: [HasMany(Lazy=true)]
20: public IList<Comment> Comments { get; set; }
21:
22: [HasAndBelongsToMany(typeof(Tag), Table = "TagPost", ColumnKey = "PostId", ColumnRef = "TagId")]
23: public IList<Tag> Tag { get; set; }
24:
25: }
调用延迟加载
前面的代码代表已经启用延迟加载,调用的时候做下修改
1: using (new SessionScope())
2: {
3: Post post = new Post();
4: post = Post.Find(1);
5: int count = post.Comments.Count;
6: foreach (var c in post.Comments)
7: {
8: Response.Write(c.Text);
9: }
10: }
需要注意 SessionScope