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

时间:2011-08-25 05:05:41

标签: 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形式写入此条件?

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

1 个答案:

答案 0 :(得分: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();

{{1}}
相关问题