【问题标题】:Unable to determine the principal end of the 'MyApp.Data.AAA_BBB' relationship. Multiple added entities may have the same primary key无法确定“MyApp.Data.AAA_BBB”关系的主体端。多个添加的实体可能具有相同的主键
【发布时间】:2016-07-20 17:10:55
【问题描述】:

我有两张桌子

create table AAA ( AAAKey int primary key, .... )
create table BBB (
  AAAKey int references AAA(AAAKey), -- Foreign key to AAA
  X      int references X  (XKey),
  ....
  primary key (AAA, X))

在 C# 中,EF 6.1.3 生成的类

[Table("dbo.AAA")]
public partial class AAA
{
  public AAA() { BBB = new HashSet<BBB>(); }
  [Key] public int AAAKey { get; set; }
  public virtual ICollection<BBB> BBB { get; set; }
}
[Table("dbo.BBB")]
public partial class BBB
{
  [Key] public int AAAKey { get; set; }
  [Key] public int XKey { get; set; }
  public virtual AAA AAA { get; set; }
}
......
protected override void OnModelCreating(DbModelBuilder medelBuilder)
{
  ....
     modelBuilder.Entity<AAA>()
            .HasMany(e => e.BBB)
            .WithRequired(e => e.AAA)
            .HasForeignKey(e => e.AAAKey)
            .WillCascadeOnDelete(false);

但是,代码在运行 SaveChanges() 时会引发 execption?

更新: 这个问题很奇怪,它只发生在某些数据上。我通过将我原来的foreach (...) {...}; SaveChange() 转换为foreach (.....) { .....; SaveChange(); } 找到了解决方案。这听起来是EF的错误吗?顺便说一句,我测试的所有数据总是有重复键插入异常,这是意料之中的。

【问题讨论】:

    标签: c# entity-framework entity-framework-6


    【解决方案1】:

    您的意思是 AAAKey 是外键,对吧?

    public partial class BBB
    {
      [ForeignKey("AAA")]
      public int AAAKey { get; set; }
      public virtual AAA AAA { get; set; }
      // other stuff...
    }
    

    【讨论】:

    • 添加FK属性后出现以下错误。 Exception thrown: 'System.InvalidOperationException' in EntityFramework.dll Additional information: The property 'AAAKey' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection&lt;T&gt; where T is a valid entity type.
    • @dc7a9163d9 我刚刚复制了你所有的代码,修复了编译问题,并添加了ForeignKey,并在我的机器上工作,所以我怀疑问题出在你没有发布的一些代码上然而。尝试创建一个完整的SSCCE 并将其发布,以便我们帮助您找到真正的问题。
    • 请查看问题中的更新。该异常仅发生在某些输入上。
    • @dc7a9163d9 即使那样,如果我没有 SSCCE 和示例输入,也很难说问题出在哪里。
    猜你喜欢
    • 2013-09-15
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2011-08-27
    • 2018-02-08
    相关资源
    最近更新 更多