Entity Framework : Filter nested collection by value of its properties

后端 未结 1 1729
无人及你
无人及你 2021-01-26 09:54

I have model as below

class MyClass()
{
   public int Id { get; set; }
   public List Items { get; set; }
}

class Item
{
     public int Id { get; s         


        
相关标签:
1条回答
  • 2021-01-26 10:33

    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();
    
    0 讨论(0)
提交回复
热议问题