使用SetFetchMode

时间:2011-07-20 05:42:45

标签: nhibernate criteria fetch

请原谅我的业余nhibernate-ness,但我正在努力获取以下情况。

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 fetch没有发生。而是在第一次访问Notification的Parameters属性时,它们被延迟加载:O

有任何帮助吗?此外,如果有一种方法使用QueryOver这样做我更喜欢。我注意到我可以去.UnderlyingCriteria.SetFetchmode(....)然而这对取得的内容没有影响。

1 个答案:

答案 0 :(得分: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>();