仅当比较可枚举项中的所有(非基元)值都包含在目标可枚举项中时才返回结果的查询
本文关键字:枚举 目标 包含 结果 查询 返回 比较 | 更新日期: 2023-09-27 18:37:05
我们有一个名为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
的List
(称为 RequiredProps),我们需要查询集合。我们希望返回满足在 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、字符串和 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();