2011-01-21 63 views
2

有沒有一種方法來實現與NHibernate ICriteria或QueryOver這樣的SQL?通過與NHibernate的ICriteria或QueryOver的聚合子查詢順序

select * 
    from [BlogPost] b 
    inner join (select blogpost_id, count(*) matchCount 
       from [Tag] 
       where name in ('tag X', 'tag Y') 
       group by blogpost_id 
      ) tagmatch 
    on tagmatch.blogpost_id = b.Id 
    order by tagmatch.matchCount desc 

目的是通過匹配標籤的數量排名的博客文章,以便與後兩者標記X標籤ÿ自帶以上只是標記X職位。

我有了這個迄今:

DetachedCriteria 
       .For<Tag>("tag") 
       .Add(Restrictions.In(Projections.Property<Tag>(x => x.Name), tags.ToArray())) 
       .SetProjection(Projections.Group<Tag>(t => t.BlogPost)) 
        .CreateCriteria("BlogPost") 
        .SetFetchMode("BlogPost", FetchMode.Eager) 
       .AddOrder(Order.Desc(Projections.RowCount())); 

然而,得到的查詢不連接抓取BlogPost。相反,它僅返回ID,當迭代BlogPost時,導致選擇n + 1。

public class BlogPost 
{ 
    ... 
    ISet<Tag> Tags {get; set;} 
} 

public class Tag 
{ 
    BlogPost BlogPost { get; set; } 
    string Name { get; set; } 
} 

This looks like a similar issue.

與NHibernate 3這是現在可能嗎?

如果沒有,是否有其他解決方案?

如有必要,我可以更改模式&域模型。如果可能,我不想使用SQL或HQL。

回答

0

我知道這個問題是前段時間提出的,但我想要做同樣的事情,請看看我的問題here,和這個傢伙here,也許你可以使用這個想法。

+0

我的問題已通過更改數據庫模式解決,但您鏈接的答案看起來像他們將解決我的問題。 – mattk 2012-06-07 11:42:25