且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架:按嵌套集合的属性值过滤

更新时间:2023-02-13 11:56:15

首先以这种方式更正您的POCO:

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}
}

用法:

提出的查询将返回所有 MyClass 实例,其中至少一个项目的 Name 将满足条件:

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();

此查询将返回所有 MyClass 实例,其中所有项的 Name 将满足条件:

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();