实体框架 - 为导航属性指定继承类型的查询

Sam*_*ens 8 c# inheritance linq-to-entities entity-framework entity-framework-4

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

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; }
}
Run Code Online (Sandbox Code Playgroud)

如何查询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();
Run Code Online (Sandbox Code Playgroud)

并获得错误"无法将类型'ChildEntity'强制转换为'ChildSubEntity'.LINQ to Entities仅支持转换实体数据模型基元类型."

我不得不满足于展平列表,并在从实体商店检索数据后应用此条件.是否有可能以实体将接受的LINQ形式写入此条件?

为了清楚起见,这是一个简化,我实际上以编程方式应用了许多条件,使用LinqKit构建查询表达式,其中一些条件在ParentEntity的属性上,一些在ParentEntity上,一些在ParentEntity的其他子实体上. .

Pio*_*cik 16

你必须使用OfType它正确解决的LINQ to Entities.将其用于ChildEntity收集并选择ParentEntities与所选ChildEntity对象相关.

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