【问题标题】:Errors with non-mapped child entity非映射子实体的错误
【发布时间】:2017-02-14 15:56:09
【问题描述】:

我有一个 ParentChild 类/表,我正在使用 Fluent API 来配置我的映射。这些表是在每个表中的非主键字段上连接的,所以根据我读过的内容,我无法在实体框架中配置连接。因此,我将手动加载我的 Parent.Children 属性 (parent.Children = (from x in context.Children...)

但是,我的 Parent 映射出现异常。我的课看起来像

public class Parent
{
   // Unique primary key
   public int ParentPrimaryKey { get; set; }

   // These two fields together compose the foreign key to join to Child
   public string ParentForeignKey1 { get; set; }
   public string ParentForeignKey2 { get; set; }

   public List<Child> Children { get; set; }
}

public class Child
{
   // Unique primary key
   public int ChildPrimaryKey { get; set; }

   // These two fields together compose the (non-unique) foreign key to join to Parent
   public string ChildForeignKey1 { get; set; }
   public string ChildForeignKey2 { get; set; }

}

当我尝试查询 context.Parents 时,我得到一个异常,因为 Entity Framework 生成的 SQL 正在尝试将 Parent 连接到 Child 并在 Child 上寻找一个名为 Child_ParentPrimaryKey 的属性。

如果我添加 modelBuilder.Entity&lt;Parent&gt;().Ignore(p =&gt; p.Children); 我得到异常 System.NotSupportedException: The specified type member 'Packages' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

如何将Children 保留为Parent 上的非映射属性而不会出错?

【问题讨论】:

  • Ignore 在这种情况下应该可以工作。我相信映射没问题,错误在查询中。 NotSupportedException 听起来您在查询中使用了未映射的集合导航属性 Packages,并且其方式不受支持。你能显示你正在使用的完整查询吗?
  • 非常感谢@V.Leon!这个问题让我发疯,你的评论指出了这个问题。我在查询中使用了Children 导航属性。我删除了它,它现在可以工作了。

标签: c# entity-framework


【解决方案1】:

您可以通过添加 [NotMapped] 属性从 EF 映射中排除属性:

using System.ComponentModel.DataAnnotations.Schema;
public class Parent {
   // ...

   [NotMapped]
   public List<Child> Children { get; set; }
}

DataAnnotations - NotMapped Attribute

【讨论】:

  • Ignore 不应该做同样的事情吗?我正在尝试将我的模型分离到他们自己的项目中,而不是让它依赖于实体框架。
  • 实际上,Ignore 也应该可以工作。您是否显示了产生错误的实际代码?因为您收到的错误消息是关于不受支持的成员“包”。 Packages 或其他自定义 C# 上是否有特殊的 getter 可能会阻止 EF 映射?
  • 对不起,实际代码中的Packages属性对应本代码中的Children属性。实际代码中Packages就是public List&lt;Order&gt; Packages { get; set; }Order在这里对应Parent
【解决方案2】:

感谢所有回复的人。您的 cmets 让我意识到问题在于我在 LINQ 查询中使用了 Parent.Children 属性。我删除了它,它现在可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2014-12-18
    • 2013-01-22
    • 1970-01-01
    • 2012-05-25
    相关资源
    最近更新 更多