如何在NHibernate中使用QueryOver选择根实体和子实体计数?

时间:2013-09-18 13:09:15

标签: nhibernate queryover

我有一个非常简单的查询我正在尝试转换为NHibernate的QueryOver语法,但我遇到了困难。原始SQL查询在功能上与:

相同
SELECT [Post].*, (
    SELECT Count(*)
    FROM [Comment]
    WHERE [Comment].[PostId] = [Post].[Id]) AS [CommentCount]
FROM [Post]

问题是我无法将其转换为QueryOver语法。我尝试定义一个包含Post和CommandCount的摘要类:

public class PostSummary
{
    public Post Post { get; set; }
    public CommentCount { get; set; }
}

然后用几个选择来定义查询:

Post lPostAlias = null;
Comment lCommentAlias = null;

var lCommentSubquery = QueryOver.Of(() => lCommentAlias)
    .Where(() => lCommentAlias.Post.Id == lPostAlias.Id)
    .ToRowCountQuery();

PostSummary lPostSummaryAlias = null;

session.QueryOver(() => lPostAlias)
    .SelectList(list => list
        .Select(x => x).WithAlias(() => lSummary.Post)
        .SelectSubQuery(lCommentSubQuery).WithAlias(() => lSummary.CommentCount)
    .List<PostSummary>();

抛出异常并显示错误消息:

could not resolve property:  of: Project.Models.Post

所以看起来它不喜欢查询的.Select(x => x)部分。我希望找到一些类似于'Projections.RootEntity()'的东西,但唉,我找不到这样的东西。

有人可以解释我做错了什么并引导我以正确的方式进行这个基本查询吗?我成像我可以选择我想要的Post的所有属性,但担心我将失去利用NHibernate为延迟加载目的生成的代理子类的能力,而不是我想要的。

1 个答案:

答案 0 :(得分:1)

使用LINQ提供程序,您可以编写

var query = from post in session.Query<Post>()
            select new PostSummary { Post = post, CommentCount = post.Comments.Count };

return query.ToList();