Reputation: 14133
Given the below sample models, I need to query the ITEMS by properties of its owner. This is Entity Frameworks sets, and I want to do this using LINQ.
public class Owner
{
public int Id { get; set; }
public string Name { get; set; }
//More than 20 other properties
}
class Item
{
public int Id { get; set; }
public string Description { get; set; }
public Owner MyOwner { get; set; }
public int idOwner { get; set; }
//Several others properties
}
I already have a PredicateBuilder with the filter of Owners.
I would like to apply this predicate (it is basically the content for where clause) to the Owner
object, in order to get all the Item
whose Owner meets the predicate condition.
If the Owner
were a list of Owners... I could use .Any(predicate)
but its cardinality is 1.
EDIT:
I'm trying to do this to avoid having to get all the Owners
that fulfill the predicate conditions and then do a Contains(idOwner)
.
db.Items.Where(c => OwnerIdsCollection.Contains(c.idOwner ?? 0));
I have seen the massive SQL CASE it creates under the hood for owners that not even have related Items
.
EDIT 2 - Predicate:
public static Expression<Func<Owner, bool>> GetPredicate(OwnerCriteria criteria)
{
var predicate = PredicateBuilder.True<Owner>();
if (criteria.Active.HasValue) {
predicate = predicate.And(p => p.Active == criteria.Active.Value);
}
//Several other criteria checkings as above
return predicate;
}
The criteria are obtained from user filters.
Then, I normally use it for querying Owners collection doing db.Owners.Where(predicate)
;
Now, conceptually, I need to do something like: db.Items.Where(x => /*Items filters*/ && x.MyOwner.Where(myOwnerPredicate))
Upvotes: 3
Views: 2107
Reputation: 6952
Can you simply try:
Items.Where(i => predicate(i.Owner))
Based on your EDIT 2:
db.Items.AsExpandable().Where(x => /*Items filters*/ && predicate.Invoke(x.Owner))
Upvotes: 1