To query both entities, you can simply join them with aliases and then use those aliases to query the properties
// alias definition
Product productAlias = null;
ProductDetail detailAlias = null;
var list = session.QueryOver<Product>(() => productAlias)
.JoinAlias(() => productAlias.ProductDetails, () => detailAlias)
.Where(() => productAlias.Code.StartsWith(search))
.And(() => detailAlias.Name.StartsWith(search))
.List();
Unfortunately nHibernate doesn't allow string.StartsWith
in this syntax so you'll have to refine the query to use .WhereRestrictionOn
and IsLike
like this:
var list = session.QueryOver<Product>(() => productAlias)
.JoinAlias(() => productAlias.ProductDetails, () => detailAlias)
.WhereRestrictionOn(() => productAlias.Code).IsLike(search, MatchMode.Start)
.AndRestrictionOn(() => detailAlias.Name).IsLike(search, MatchMode.Start)
.List();
:Edit: Just found that you want an OR query, to do this we have to combine to restrictions within the Where statement like:
var listWithOr = session.QueryOver<Product>(() => productAlias)
.JoinAlias(() => productAlias.ProductDetails, () => detailAlias)
.Where(Restrictions.On(() => productAlias.Code).IsLike(search, MatchMode.Start)
|| Restrictions.On(() => detailAlias.Name).IsLike(search, MatchMode.Start))
.List();
Hope this helps
:Edit2: The above query will not give you a distinct result, some products can occur in the list multiple times, you'll have to make it a distinct result if needed...
The same query (with already distinct result) can be achieved with a simple NHibernate.Linq
statement:
var list2 = session.Query<Product>()
.Where(prod => prod.Code.StartsWith(search) ||
prod.ProductDetails.Any(detail => detail.Name.StartsWith(search))
);