我想使用条件重现以下查询:
select a.ID as article, count(c.ID) as commentsCount
from Comments c
left outer join Articles a on a.ID=c.ArticleID
where a.ID in (2,10)
group by a.ID
我写了它,但在某处我必须有错误,因为结果与我预期的不同。
标准:
ICriteria criteria = Session.CreateCriteria<Comment>("c")
.CreateCriteria("Article", "a",
NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.Add(Restrictions.In("a.ID", articleIDs))
.SetProjection(Projections.Property("a.ID"))
.SetProjection(Projections.Count("c.ID"))
.SetProjection(Projections.GroupProperty("a.ID"));
NHibernate使用以下标准生成以下sql:
SELECT a1_.ID as y0_
FROM Comments this_
left outer join Articles a1_
on this_.ArticleID = a1_.ID
WHERE a1_.ID in (2 /* @p0 */,10 /* @p1 */)
GROUP BY a1_.ID
映射:
public class Comment : EntityBase<int>
{
public virtual Article Article { set; get; }
}
public CommentMap()
{
Id(x => x.ID).GeneratedBy.Identity();
References(x => x.Article).Not.Nullable()
.LazyLoad().Cascade
.SaveUpdate().Column("ArticleID");
}
答案 0 :(得分:3)
每次使用SetProjection
时,都会替换上一个。
您需要使用:
.SetProjection(Projections.Property("a.ID"),
Projections.Count("c.ID"),
Projections.GroupProperty("a.ID"))