问题
I have model as below
class MyClass()
{
public int Id { get; set; }
public List<Item> Items { get; set; }
}
class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
both are added to DBContext as DbSets, now I would like to filter out the MyClass using the value of the Name property in the Items collection. How do I do this?
回答1:
First of all correct your POCOs this way:
public class MyClass
{
public int Id { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public virtual MyClass MyClass {get;set}
public int MyClassId {get;set}
}
Usage:
Presented query will return all MyClass instances, where at least one item's Name will satisfy condition:
var answer = db.MyClass.Where(c => c.Items.Any(item => item.Name == "Sam")).ToList();
This query will return all MyClass instances, where all item's Name will satisfy condition:
var answer = db.MyClass.Where(c => c.Items.All(item => item.Name == "Sam")).ToList();
来源:https://stackoverflow.com/questions/47002517/entity-framework-filter-nested-collection-by-value-of-its-properties