Welcome

首页 / 软件开发 / .NET编程技术 / Castle ActiveRecord学习实践(6) 延迟加载和使用Where子句

Castle ActiveRecord学习实践(6) 延迟加载和使用Where子句2011-02-03 cnblogs terrylee摘要:在ActiveRecord中把数据库表之间的关联关系采用对象间的聚合关系来表现,然而这却带来一系列的性能上的问题。就像我在One-Many中用到的例子Blog,使用Blog.Find(1)查找了一个Blog对象,也许我们只用到它,但事实它却把该Blog所关联的Post对象也读取出来放在了内存中,于是我们就需要有一种方法来实现只在需要Post对象的时候框架再自动读取。另外ActiveRecord只提供了Find(id),FindAll()这样两个静态的查询方法,在我们查询中还远远不够,这方面ActiveRecord为我们提供了HQL语言的支持,同时也可以通过设置Where子句来实现一些简单的查询。

主要内容

1.实现延迟加载

2.使用Where子句

一.实现延迟加载

要实现延迟加载,其实只要在HasMany特性中使用Lazy=true就可以了。来看我们的Blog类是如何声明的:

[ActiveRecord("Blogs")]
public class Blog : ActiveRecordBase
{
private int _id;

private String _name;

private String _author;

private IList _posts;

[PrimaryKey(PrimaryKeyType.Identity, "blog_id")]
public int Id
{
get { return _id; }
set { _id = value; }
}

[Property("blog_name")]
public String Name
{
get { return _name; }
set { _name = value; }
}

[Property("blog_author")]
public String Author
{
get { return _author; }
set { _author = value; }
}

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

public static void DeleteAll()
{
DeleteAll( typeof(Blog) );
}

public static Blog[] FindAll()
{
return (Blog[]) FindAll( typeof(Blog) );
}

public static Blog Find(int id)
{
return (Blog) FindByPrimaryKey( typeof(Blog), id );
}
}