【问题标题】:Nhibernate Query Select only those exist in the Child table at lease oneNhibernate Query 仅选择至少存在于 Child 表中的那些
【发布时间】:2015-12-17 04:45:16
【问题描述】:

我的 Nhibernate 查询有问题。

我的 XML 映射

我有 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)
    )
); 

有什么建议吗?

【问题讨论】:

标签: nhibernate queryover nhibernate-criteria


【解决方案1】:

我们可以使用子查询和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 几乎是一样的...

【讨论】:

  • 亲爱的 Radim Köhler, Finnaly 我通过使用 query.Add(Restrictions.Eq("Field3", true)) .Add( Subqueries.PropertyIn( "ID", DetachedCriteria .For() .SetProjection(Projections.Property("TableA.ID")) ) );
  • 很高兴看到我的回答对您有所帮助
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多