本文介绍了实体框架:按嵌套集合的属性值过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型如下

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

都以 DbSets 的形式添加到 DBContext 中,现在我想使用 Name的值过滤掉 MyClass Items 集合中的属性.我该怎么做?

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?

推荐答案

首先以这种方式更正您的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();

这篇关于实体框架:按嵌套集合的属性值过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 04:29