繁体   English   中英

无法确定关系的主要终点,多个添加的实体可能具有相同的主键

[英]Unable to determine the principal end of the relationship, Multiple added entities may have the same primary key

抱歉,首先让我说我确实尝试过在线搜索此问题,但有一些与我的情况没有特别关系。 我花了几个小时,不知道。

我在下面发布了我的代码,删除了所有不相关的信息

首先,这是我的课程

public class StudentDm
{
    public int Id { get; set; }
    public virtual List<StudentParentDm> StudentParents { get; set; }

    // other properties ...
}

// constructs a many to many relationship with some additional info in this model
public class StudentParentDm : EntityBaseDm
{
    public int Id { get; set; }
    public int StudentId { get; set; }
    public virtual StudentDm Student { get; set; }
    public int ParentId { get; set; }
    public virtual ParentDm Parent { get; set; }

    // other properties ...
}

public class ParentDm
{
    public int Id { get; set; }

    // other properties ...
}

对应:

public StudentMap()
{
    HasMany(m => m.StudentParents).WithRequired().HasForeignKey(m => m.StudentId).WillCascadeOnDelete(false);
}

public StudentParentMap()
{
    HasRequired(m => m.Student).WithMany().HasForeignKey(m => m.StudentId).WillCascadeOnDelete(false);
    HasRequired(m => m.Parent).WithMany().HasForeignKey(m => m.ParentId).WillCascadeOnDelete(false);
}

public ParentMap()
{
    HasMany(m => m.StudentParents).WithRequired().HasForeignKey(m => m.ParentId).WillCascadeOnDelete(false);
}

然后是代码,我在这里尝试为学生创建多个新的StudentParent,每个都有自己的新Parent。

foreach (StudentParentDm studentParent in studentParents) // foreach new studentParent
{
    StudentParentDm trackedStudentParent;
    if (studentParent.Id == 0)
    {
        trackedStudentParent = new StudentParentDm
        {
            Parent = new ParentDm()
        };

        // map from studentParent to trackedStudentParent, including the Parent
        // ...

        trackedStudent.StudentParents.Add(trackedStudentParent);
    } else 
    {
        // unimportant
    }
}

unitOfWork.Commit() // blows up with error message

然后我收到此消息:

Unable to determine the principal end of the 'Cobro.BusinessObjects.DatabaseContextServices.ParentDm_StudentParents' relationship. Multiple added entities may have the same primary key.

仅当我尝试一次添加多个StudentParent时,才会发生这种情况。 我不确定为什么StudentParents的数量会很重要? 我认为我的关系建立正确。

它也可以与添加多个StudentGrades一起使用,但是区别在于StudentGrade模型是扁平的(没有像StudentParent这样的任何孩子都有Parent)

由于没有人回答。 如果我发现了什么可以帮助任何人的话,请贴上我的发现。

在StudentParentMap中,添加

m => m.Parent

这样

HasMany(m => m.StudentParents).WithRequired(m => m.Parent).HasForeignKey(m => m.ParentId).WillCascadeOnDelete(false);

不知道为什么这很重要..映射似乎足够,以至于代码优先生成的数据库关系不会随着新的添加而改变。 但是,EF需要弄清楚如何在添加多个记录的事务期间配置FK。 对我来说,这很微妙。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM