Nhibernate查询仅选择Child表中存在的至少一个

时间:2015-12-17 04:45:17

标签: nhibernate queryover nhibernate-criteria

我的Nhibernate查询有问题。

我的XML映射

enter image description here

enter image description here

我有2个表,TableA(KeyField1,Field2,Field3)和TableB(KeyField1,DateField)

TableA
------------------
KeyField1 | Field2  | Field 3
K1        | A1      | True
K2        | A2      | True
K3        | A3      | True
K4        | A4      | False





TableB
-------------------------------------------------------------
TableBID                             | KeyField1 | DateField
9CFA1E9F-7680-4715-BD5B-8DE674DB6EA6 | K1        | 12/17/2010
11C8226E-AEF2-4042-AADD-BDDBA35D83D6 | K3        | 12/17/2010
3971C949-673E-4FE5-B9B4-D73949F2FC53 | K3        | 12/21/2010

我希望得到像这样的结果

TableA
------------------
KeyField1 | Field2  | Field 3
K1        | A1      | True
K3        | A3      | True

意味着我想在TableA中拥有所有记录,其中只有一个记录存在于TableB中。

我试过这种方式但没有成功

DetachedCriteria query = DetachedCriteria.For(typeof(TableA), "_request");
query.CreateAlias("TableB", "pl");
query.Add(
    Restrictions.And(    
        Restrictions.Eq("Field3", true),
        Restrictions.Gt( Projections.Count("pl.ID") , 0)
    )
); 

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我们可以使用子查询和EXISTS语句

TableA parent = null;
TableB child = null;

// parent query (TableA)
// will be filtered by existing children
// but still will be ready for paging
var parentQuery = session.QueryOver<TableA>(() => parent)
    .WithSubquery
    .WhereExists(
        // subquery, where we assure that child exists for parent ID
        QueryOver.Of<TableB>(() => child)
            .Where(() => child.TableA.ID == parent.ID)
            .Select(_ => child.ID)
    );

// parents which fit to our needs
IList<TableA> result = parentQuery
    .Take(10)
    .Skip(0)
    .List<TableA>();

这是QueryOver语法和ICriteria几乎相同......

相关问题