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