具有别名的nHibernate QueryOver - 无法基于IList<>执行查询别号

时间:2015-11-23 19:06:34

标签: c# fluent-nhibernate

我在构建查询时遇到问题。

这是架构:

  

表B 1 - < - > * TableA

public class TableB
{
    public virtual IList<TableA> TableAData { get; set; }
}

mapping:
HasMany(x => x.TableAData).KeyColumn("TableAData_ID");

public class TableA
{
    public virtual TableB ConnectedTableB_Item { get; set; }
}

mapping:
References(x => x.ConnectedTableB_Item, "ConnectedTableB_ID");

并且questy很简单 - 我需要加载那些TableB计数为0的TableA

IList<TableA> tableA_Alias = null;
TableB tableB_Alias = null;

var query = Session.QueryOver<TableB>(() => tableB_Alias)
                   .JoinAlias(() => tableB_Alias.TableAData, () => tableA_Alias)
                   .Where(x => tableA_Alias.Count == 0);

但是我得到了例外

could not resolve property: Count of: TableA

我还尝试将IList<TableA> tableA_Alias更改为TableA tableA_Alias

TableA tableA_Alias = null;
TableB tableB_Alias = null;

var query = Session.QueryOver<TableB>(() => tableB_Alias)
                   .JoinAlias(() => tableB_Alias.TableAData, () => tableA_Alias)
                   .Where(x => tableA_Alias == null);

然后我收到错误

Object reference not set to an instance of an object

(显然因为tableA_Alias为空)。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

对于优化,您可能希望在父对象上创建readonly属性,然后映射到公式(子查询)。

public class Parent {
  public virtual IList<Child> Children { get; set; }
  public virtual int TotalChildren { get; set; }
}

并将其映射为:

Map(t => t.TotalChildren).Formula("SELECT COUNT(*) FROM ChildTable WHERE ChildTable.ParentId = ParentId");