ActiveRecord 中HQL也就是NHibernate中的HQL,可用来查询实体。
简单的HQL写法如下:
public static Post[] GetPosts(int id)
{
SimpleQuery<Post> q = new SimpleQuery<Post>(@"from Post p where p.OwnerBlog.id = ?", id);
return q.Execute();
}
public static int[] GetPostIdsFromInterval(int start, int end)
{
SimpleQuery<int> q = new SimpleQuery<int>(typeof(Post), @"select p.Id from Post p where p.Id between :start and :end");
q.SetParameter("start", start);
q.SetParameter("end", end);
return q.Execute();
}
public int CurrentPostMax()
{
ScalarQuery<int> q = new ScalarQuery<int>(typeof(Post), @"select max(p.Id) from Post p where p.OwnerBlog = ?", this);
return q.Execute();
}
其中SimpleQuery为简单的查询类,而ScalarQuery为简单的查询单个字段值的类。当然ActiveRecord可用NHibernate的查询方法,代码如下:
public static Post[] GetPostsFromAuthor(String author)
{
return (Post[])Execute
(
delegate(ISession session, object instance)
{
IQuery query = session.CreateQuery("from Post p where p.OwnerBlog.Name = :author");
query.SetString("author", (String)instance);
IList results = query.List();
Post[] posts = new Post[results.Count];
results.CopyTo(posts, 0);
return posts;
},
author
);
}
要了解HQL更多知识,请参考NHibernate官方文档。