2010-11-30 79 views
3

我使用的是Nhibernate v2.1.2.4000。隨着標籤帖子之間的許多一對多的關係,我有查詢:Linq to NHibernate - 訂購匿名類型

tags 
.Select(t => new { Name = t.Name, Count = t.Posts.Count }) 
.OrderBy(x => x.Count); 

訂購匿名類型失敗(引用不設置到對象的實例)。這個問題與LinqToNH有關嗎?什麼可能是這個錯誤的來源?解決辦法是什麼? 如果它與LinqToNH有關,那麼如何用其他選項(即Criteria API)解決它?

編輯:當我嘗試亞當的ICriteria選項,SqlProfiler說執行的腳本是:

SELECT this_.Name as y0_, count(this_.Id) as y1_ FROM Tag this_ GROUP BY this_.Name ORDER BY count(this_.Id) asc 

的映射標籤:

public class TagMap : ClassMap<Tag> 
{ 
    public TagMap() 
    { 
     Table("Tag"); 
     Id(x => x.Id).GeneratedBy.GuidComb(); 
     Map(x => x.Name); 
     HasManyToMany(x => x.Posts) 
      .Table("PostTags") 
      .ChildKeyColumn("Post") 
      .ParentKeyColumn("Tag") 
      .Cascade.None().Inverse(); 
    } 
} 

回答

2

有在NHibernate.Linq許多事情的NHibernate 2.1.2.4000那是行不通的。您可以使用HQL或ICriteria,或者升級到NHibernate 3.0,或者如果您要使用所有數據,請在Select之後通過添加ToList強制執行您的Linq查詢。

tags 
    .Select(t = new { t.Name, t.Posts.Count }) 
    .ToList() 
    .OrderBy(x => x.Count); 

匿名對象本身就是NHibernate.Linq可以處理的東西。

順便說一下,如果與匿名對象中的字段/屬性相同,則不必在匿名對象中指定字段名稱。

編輯:此查詢的版本的ICriteria是這樣的......

var tags = session.CreateCriteria(typeof(Tag), "tag") 
    .SetProjection(
     Projections.GroupProperty("tag.Name"), 
     Projections.Count("tag.Posts")) 
    .AddOrder(Order.Asc(Projections.Count("tag.Posts"))) 
    .List(); 

編輯:有了正確的映射,我得到同樣的SQL,拱門。我之前的地圖是錯誤的。然而,這似乎工作。

var tags = session.CreateCriteria(typeof(Tag), "tag") 
    .CreateCriteria("tag.Posts", "post") 
    .SetProjection(
     Projections.GroupProperty("tag.Name"), 
     Projections.Count("post.Id")) 
    .AddOrder(Order.Asc(Projections.Count("post.Id"))) 
    .List(); 

我得到的SQL是這樣的......

SELECT this_.Name as y0_, count(post1_.Id) as y1_ FROM Tag this_ inner join Post_Tags posts3_ on this_.Id=posts3_.Tag inner join Post post1_ on posts3_.Post=post1_.Id GROUP BY this_.Name ORDER BY count(post1_.Id) asc 
+0

切換。不幸的是,升級到3.0不是目前的選擇。如何使用Criteria API編寫它?我也編輯了Criteria API選項的問題。 – rovsen 2010-12-01 21:02:44

+0

亞當,當我嘗試結果集計數ICriteria版本總是1,雖然不是所有他們都是1.你知道爲什麼會發生這種情況嗎? – rovsen 2010-12-02 21:57:53

1

嘗試訂貨,然後再進行選擇。我在2.1.2.4上有非常類似的查詢,可以很好地工作。

編輯:也嘗試感謝您的回答CountCount()之間