【问题标题】:Entity Framework - query specifying inherited type for navigation property实体框架 - 查询指定导航属性的继承类型
【发布时间】:2011-08-25 05:05:41
【问题描述】:

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

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 的其他子实体。

【问题讨论】:

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


    【解决方案1】:

    您必须使用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();
    

    【讨论】:

    • 好答案。但是,我在 ParentEntity 上还有许多其他标准需要满足,我将编辑问题以明确这一点。
    • 只需在SelectMany 中添加Where 即可过滤ParentEntity
    • 哦,现在很有趣。我会玩一会然后回复你。
    • 我在使用我的工作单元框架时遇到了一些麻烦,但这是我的问题,不是你的问题 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多