Entity Framework : Filter nested collection by value of its properties

。_饼干妹妹 提交于 2020-01-22 03:24:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!