Reputation: 1517
I am trying to write a linq query which will exclude any records that have a child record with a certain integer ID.
The class I am querying against looks like:
public class Group {
public ICollection<Item> { get; set; } // This is the child collection
}
public class Item {
public int Id { get; set; }
}
My repository query method is:
public ICollection<Group> Get(int itemId) {
return from c in Set.... // Set is an EF collection of all Groups
}
I want to return all Groups
that do not have an Item
in their Items
collection with the Id
equal to the itemId
passed to the method.
Not sure how to write this most efficiently in Linq.
Upvotes: 3
Views: 771
Reputation: 14488
This will work (I'm using method syntax though as I prefer method syntax above query syntax for anything other than joins):
var result = db.Groups.Where(g => !g.Items.Any(i => i.Id == itemID)).ToList();
Select all groups which don't contain an item with an Id
equal to itemID
. By the way I notice you have Set
in your code? Does this mean you already fetched all the groups beforehand or something (so filtering in memory)? The easiest way is to work with your DbContext
and access your tables from there.
Upvotes: 2