简体   繁体   中英

nHibernate QueryOver with alias - can't execute query based on IList<> alias

I have a problem with building query.

Here's the schema:

TableB 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");

and the questy is simple - I need the load those TableB items, whose TableA count is 0

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

but I get the exception

could not resolve property: Count of: TableA

I tried also to change from IList<TableA> tableA_Alias to 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);

but then I get an error

Object reference not set to an instance of an object

(obviously because the tableA_Alias is null).

How can I fix it ?

For optimization you might want to create readonly property on parent object then map to formula (subquery).

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

And map it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM