c# - 仅当来自比较可枚举的所有(非原始)值都包含在目标可枚举中时才返回结果的查询

标签 c# linq entity-framework entity-framework-4 linq-to-entities

我们有一个类型为 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/

相关文章:

c# - 使用 Linq to Entities 实现 DateTime.ToString(string)

c# - 位数组到字符串再返回位数组

c# - 一种使我的 Parallel.ForEach 线程安全的更好方法?

c# - 是否可以返回列表中具有最小属性的对象?

c# - 哪种 IEnumerable To a List 方式更好?

c# - 用于多级查询的动态 Linq 表达式

entity-framework - 使用 Entity Framework 时,我应该使用部分类作为业务层吗?

.net - 将 EF6 连接到 Oracle 11g DB 时不会显示数据源名称

c# - 来自资源文件的 iTextSharp pdf 图像

C# 创建与处理器一样多的类实例