c# - Entity Framework - 为导航属性指定继承类型的查询

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

所以我有一个具有导航属性的实体,该属性的类型具有类层次结构。 (更改实体名称以保护罪犯)

class ParentEntity
{
  virtual ChildEntity TheProperty { get; set; }
  virtual string AnotherProperty { get; set; }
  virtual string AnotherProperty2 { get; set; }
}

class ChildEntity
{
}

class ChildSubEntity : ChildEntity
{
  virtual string InterestingProperty { get; set; }
}

我如何查询 ParentClass 实体,我的查询条件之一是 TheProperty 是 ChildSubClass 类型且 InterestingProperty 具有特定值?

我试过了

ObjectContext context = GetContext();
var result = context.ParentEntities.
  Where(e => e.AnotherProperty == AnotherInterestingValue).
  Where(e => e.TheProperty is ChildSubEntity).
  Where(e => ((ChildSubEntity)e.TheProperty).
    InterestingProperty == InterestingValue).
  ToList();

并收到错误“无法将类型‘ChildEntity’转换为类型‘ChildSubEntity’。LINQ to Entities 仅支持转换实体数据模型基元类型。”。

我不得不满足于展平列表,并在从实体存储中检索到数据后应用此条件。是否可以将此条件写成 LINQ to Entities 可以接受的形式?

需要说明的是,这是一种简化,我实际上以编程方式应用了一些条件,使用 LinqKit 构建查询表达式,其中一些条件针对 ParentEntity 的属性,一些针对 ParentEntity,还有一些针对 ParentEntity 的其他子实体。

最佳答案

您必须使用 OfType,它由 LINQ to Entities 正确解析。针对 ChildEntity 集合使用它并选择与所选 ChildEntity 对象相关的 ParentEntities

ObjectContext context = GetContext();
var result = context.ChildEntities.OfType<ChildSubEntity>
.Where(e => e.InterestingProperty == InterestingValue)
.SelectMany(e = > e.ParentEntity)
.ToList();

关于c# - Entity Framework - 为导航属性指定继承类型的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7185393/

相关文章:

c# - 找到等于给定总和的正数和负数的所有可能组合

c# - 如何在传递时修改 DbContext 基本构造函数参数?

c# - Identity Core 与 Entity Framework 6

c# - 列出文件中的所有#region

c# - 从引用的程序集中读取 .resx 文件名

PHP - 对象实例化上下文 - 奇怪的行为 - 是 PHP 错误吗?

typescript - 继承自错误中断 `instanceof` 检查 TypeScript

java - 根据类实例进行操作

c# - 在 C# 中遍历树的微优化

c# - 高效的 LINQ to Entities 查询