获取具有所有列表成员的对象的多对多 linq 查询
Ef many to many linq query that gets objects that have all list members
我正在使用 entity framework。我有两个领域模型。
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Feature> Features { get; set; }
}
public class Feature
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Animal> Animals { get; set; }
}
动物和特征具有多对多关系,所以我在数据库中有这些表:
- 动物
- 特征
- 动物特征
我得到一个列表
var featureList = new List<Feature> { new Feature { Name = "f1" }, new Feature { Name = "f2" } };
我如何获得包含 所有特征 的动物列表 featureList
如有任何帮助,我们将不胜感激。我坚持这个真的很糟糕。
您可以尝试这样的操作:
var features = { "f1","f2" };
var query = from a in dc.Animals
where ( from f in a.Features
where features.Contains(f.Name)
select f).Count() == features.Length
select a;
我建议您使用原始类型集合而不是 Features
的列表,因为当您需要检查特定集合中是否包含多个元素时,EF 仅适用于原始类型和枚举类型。您无法在 where
条件下比较两个自定义对象。请记住,此查询将被转换为 sql,而 EF 不知道如何转换两个对象之间的比较。所以,正如我之前所说,您应该在这种查询中使用原始类型或枚举类型。您可以 select 您需要拥有动物的特征的名称或 ID,然后像我上面那样与该集合进行比较。
无论如何,我认为您也可以使用 Any
扩展方法进行另一个查询:
var featureList = new List<Feature> { new Feature { Name = "f1" }, new Feature { Name = "f2" } };
var query = from a in dc.Animals
where ( from f in a.Features
where featureList.Any(e=>e.Name==f.Name)
select f).Count() == featureList.Count
select a;
但我特别喜欢第一种。
我正在使用 entity framework。我有两个领域模型。
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Feature> Features { get; set; }
}
public class Feature
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Animal> Animals { get; set; }
}
动物和特征具有多对多关系,所以我在数据库中有这些表:
- 动物
- 特征
- 动物特征
我得到一个列表
var featureList = new List<Feature> { new Feature { Name = "f1" }, new Feature { Name = "f2" } };
我如何获得包含 所有特征 的动物列表 featureList
如有任何帮助,我们将不胜感激。我坚持这个真的很糟糕。
您可以尝试这样的操作:
var features = { "f1","f2" };
var query = from a in dc.Animals
where ( from f in a.Features
where features.Contains(f.Name)
select f).Count() == features.Length
select a;
我建议您使用原始类型集合而不是 Features
的列表,因为当您需要检查特定集合中是否包含多个元素时,EF 仅适用于原始类型和枚举类型。您无法在 where
条件下比较两个自定义对象。请记住,此查询将被转换为 sql,而 EF 不知道如何转换两个对象之间的比较。所以,正如我之前所说,您应该在这种查询中使用原始类型或枚举类型。您可以 select 您需要拥有动物的特征的名称或 ID,然后像我上面那样与该集合进行比较。
无论如何,我认为您也可以使用 Any
扩展方法进行另一个查询:
var featureList = new List<Feature> { new Feature { Name = "f1" }, new Feature { Name = "f2" } };
var query = from a in dc.Animals
where ( from f in a.Features
where featureList.Any(e=>e.Name==f.Name)
select f).Count() == featureList.Count
select a;
但我特别喜欢第一种。