我们有一个类型为 Unit 的实体集合、一个类型为 UnitProp 的实体集合和一个类型为 Prop 的实体集合像这样定义(简化):
class Unit
{
int ID;
ICollection<UnitProp> UnitProps;
}
class UnitProp
{
int ID;
int UnitID;
Unit Unit;
int PropID;
Prop Prop;
}
class Prop
{
int ID;
string Description;
}
我们有一个包含Prop
(称为RequiredProps)的List
,我们需要用它来查询集合。我们想要返回满足在 RequiredProps 中指定所有 Prop
的条件的 Unit
集合。
我这样写查询:
var result = ctx.Units
.Where(x => RequiredProps.AsEnumerable()
.Except(x.UnitProps.Select(y => y.Prop))
.Count() == 0)
.ToList();
当然,这是 Linq to Entities,因此查询会抛出异常: 无法创建“Prop”类型的常量值。在此上下文中仅支持基本类型(“例如 Int32、String 和 Guid”)。
我也试过这个:
var result = ctx.Units
.Where(x => RequiredProps.Select(y => y.ID)
.Except(x.UnitProps
.Select(y => y.Prop)
.Select(y => y.ID))
.Count() == 0)
.ToList();
...但它产生了相同的异常。
建议?
最佳答案
var requiredIds = RequiredProps.Select(y => y.ID);
var result = ctx.Units
.Where(m => !requiredIds
.Except(m.UnitProps.Select(x => x.Prop.ID)))
.Any())
.ToList();
关于c# - 仅当来自比较可枚举的所有(非原始)值都包含在目标可枚举中时才返回结果的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032928/