2011-07-20 23 views
2

打擾我的業餘nhibernate-ness,但我在下面的場景中抓取掙扎。使用SetFetchMode

var query = session.CreateCriteria<Notification>().SetFetchMode("Parameters", FetchMode.Select) 
.CreateAlias("Parameters", "p", JoinType.InnerJoin) 
.Add(Restrictions.Where<Notification>(x => x.Acknowledged == false)); 

[一些建立一個IList代碼調用npHashes]

query = query.Add(Restrictions.In("p.PairHash", npHashes)).AddOrder(new Order("DateCreated", false)); 

[枚舉它]

請注意,我使用SELECT作爲prefetchmode ......,顯然就剩一個選項超出QueryOver ...和LINQ ...還要注意,獲取的表是與我已加入過濾的表相同的表。

執行該查詢的結果是:

SELECT 
    this_.Id as Id14_1_, 
    this_.Version as Version14_1_, 
    this_.Url as Url14_1_, 
    this_.DispatchType as Dispatch5_14_1_, 
    this_.Acknowledged as Acknowle6_14_1_, 
    this_.DateCreated as DateCrea7_14_1_, 
    this_.NotificationType as Notifica2_14_1_, 
    p1_.Id as Id15_0_, 
    p1_.Version as Version15_0_, 
    p1_.NotificationId as Notifica3_15_0_, 
    p1_.Name as Name15_0_, 
    p1_.Value as Value15_0_, 
    p1_.PairHash as PairHash15_0_ 
FROM 
    Notification this_ 
inner join 
    NotificationParameter p1_ 
     on this_.Id=p1_.NotificationId 
WHERE 
    this_.Acknowledged = ?p0 
    and p1_.PairHash in (
     ?p1 
    ) 
ORDER BY 
    this_.DateCreated desc; 
?p0 = False [Type: Boolean (0)], 
?p1 = 'V3zmXnv12B3AC26xeG10w+bas4U=' [Type: String (28)] 

所以第一個問題是,由於某種原因,NotificationParameter列包含在選擇列表...這似乎不是做一個選擇取回。這是不好的,因爲a)我想要一個選擇提取b)提取記錄被過濾。提取與加入(作爲一個概念)並不相同,並且加入的數據上的過濾器不應該(在這種情況下)過濾我提取的內容。

當然第二個問題是沒有發生SELECT提取。取而代之的是第一次訪問通知的Parameters屬性,它們被延遲加載:O

任何幫助?此外,如果使用QueryOver的方式來做到這一點,我寧願這樣做。我注意到,我可以去.UnderlyingCriteria.SetFetchmode(....),但是這對獲取的內容沒有影響。

回答

3

在SQL你不能過濾和同時獲取所有。我還沒有熟悉查詢,但你應該明白。

var subquery = DetachedCriteria.For<Notification>() 
    .CreateAlias("Parameters", "p", JoinType.InnerJoin) 
    .Add(Restrictions.Where<Notification>(x => x.Acknowledged == false)) 
    .Add(Restrictions.In("p.PairHash", npHashes)) 
    .SetProjection(Projections.Id()); 

session.CreateCriteria<Notification>() 
    .Add(Subqueries.PropertyIn("Id", subquery)) 
    .SetFetchMode("Parameters", FetchMode.Eager) 
    .AddOrder(Order.Asc("DateCreated")) 
    .List<Notification>(); 
+0

我會嘗試一下...但是,因爲我正在做一個SELECT提取(不是急於與我認爲映射到外部聯接)過濾和提取相同應該不會相互影響。 – Sam