所以我有一个具有导航属性的实体,该属性的类型具有类层次结构。 (更改实体名称以保护罪犯)
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/