NHibernate:Criteria - 获取子id的列表

时间:2011-04-01 23:17:35

标签: nhibernate icriteria

我有很多关系的实体。 给定父ID,我如何使用ICriteria检索子列表?

到目前为止

代码:

var driverList = DriverGroup.CreateCriteria()
    .Add(Restrictions.IdEq(groupId))
    .SetFetchMode("Drivers", FetchMode.Eager)
    .SetResultTransformer(Transformers.DistinctRootEntity)
    .UniqueResult<DriverGroup>().Drivers.Select(x => x.Id).
    ToArray();

var criteria = Driver.CreateCriteria()
    .Add(Restrictions.In("Id", driverList));

但是,生成的SQL是:

SELECT
    this_.groupId as groupId5_1_,
    this_.name as name5_1_,
    this_.type as type5_1_,
    drivers2_.groupId as groupId3_,
    ... fields snipped ...
    drivers3_.userId as ID3,
    ... fields snipped ...
FROM
    dbo.Groups this_ 
left outer join
    dbo.Object_Rel drivers2_ 
        on this_.groupId=drivers2_.groupId
left outer join
    dbo.vwDriverSimple driverbase3_ 
        on drivers2_.ID=driverbase3_.userID 
WHERE
    this_.type=0 AND this_.groupId = @p0;
@p0 = 443 [Type: Int32 (0)]


SELECT
    this_.userID as userID10_1_,
    ... fields snipped ...
FROM
    dbo.drivers this_ 
WHERE
    this_.userID in (
        @p0, ... lots of parameters ...);

如何让它生成以下内容?

SELECT
    this_.userID as userID10_1_,
    ... fields snipped ...
FROM
    dbo.drivers this_ 
WHERE
    this_.userID in (
        SELECT
            drivers3_.userId as ID3
        FROM
            dbo.Groups this_ 
        left outer join
            dbo.Object_Rel drivers2_ 
                on this_.groupId=drivers2_.groupId
        left outer join
            dbo.vwDriverSimple driverbase3_ 
                on drivers2_.ID=driverbase3_.userID 
        WHERE
            this_.type=0 AND this_.groupId = @p0;
        @p0 = 443 [Type: Int32 (0)]
);

1 个答案:

答案 0 :(得分:0)

轻松,直接查询孩子。

IList<Driver> driverList = Drivers.CreateCriteria()
    .Add(Restrictions.Eq("Group.Id", groupId)) <-- modify according to your domain mapping
    .SetProjection(Projections.Property("Id"))
    .SetResultTransformer(Transformers.DistinctRootEntity)
    .List<Driver>();