简体   繁体   中英

NHibernate QueryOver Entity with IList properties sub property

Having the following classes;

public class Customer{
  ....
  ....
  IList<Receipt> Receipts { get; set; }
}

public class Receipt{
  ....
  IList<SoldProduct> Products { get; set; }
}

Having this said, my problem is that I'm trying to query the customer that has bought a specific product. When I try to execute the following code I get a NullReferenceException.

Customer c = null;
Receipt r = null;
SoldProduct sP = null;

var queryOver = Session.QueryOver(() => c)
    .JoinAlias(() => c.Receipts, () => r)
    .JoinAlias(() => r.SoldProducts, () => sP)
    .Where(() => c.Name.IsLike(query.Search, MatchMode.Anywhere) ||
                           c.Surname.IsLike(query.Search, MatchMode.Anywhere) ||
                           c.Address.IsLike(query.Search, MatchMode.Anywhere) ||
                           c.Receipts.Select(receipt => 
                           receipt.SoldProducts.Select(product => product.Product.OldId.ToString()))
                           .SingleOrDefault().Single().IsLike(query.Search, MatchMode.Anywhere))

I'm just stuck right now. I might be missing a key point like here if so please let me know. If there is actually a easier way to execute this query I would really appreciate any help.

Try to apply filter to product alias:

Customer c = null;
Receipt r = null;
SoldProduct sP = null;
Product p = null;

var queryOver = Session.QueryOver(() => c)
    .JoinAlias(() => c.Receipts, () => r)
    .JoinAlias(() => r.SoldProducts, () => sP)
    .JoinAlias(() => sp.Product, () => p)
    .Where(() => c.Name.IsLike(query.Search, MatchMode.Anywhere) ||
                           c.Surname.IsLike(query.Search, MatchMode.Anywhere) ||
                           c.Address.IsLike(query.Search, MatchMode.Anywhere) ||
                           p.OldId.ToString().IsLike(query.Search, MatchMode.Anywhere))

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