0..1 到 N 引用关系 -> 错误消息我不明白

0..1 to N Referencing Relation -> Error Message I don't understand

问题是我收到一条错误消息:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Users_dbo.People_Id". The conflict occurred in database "TrialDb", table "dbo.People", column 'Id'

我尝试执行以下操作:

关系应该是单向的,这意味着 User 不需要 Person 的导航 属性。

我正在做的是尝试将 User 添加到我的数据库,这导致了上述错误。

这里是 UserPerson class 定义(缩写)

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

    public int? PersonId {get; set; }
    public virtual Person Person {get; set;}

    // two self-refencing properties
    public int CreatorId {get; set; }
    public virtual Person Creator{get; set;}

    public int ChangingUserId {get; set; }
    public virtual Person ChangingUser {get; set;}

    public byte[] RowVersion {get; set;}
}

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

    public virtual ICollection<User> Users {get; set;}

    public byte[] RowVersion {get; set;}
}

我对两个实体的配置classes如下:

 public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap ()
    {
        HasRequired (p => p.Creator).WithRequiredPrincipal ().WillCascadeOnDelete (false);
        HasRequired (p => p.ChangingUser).WithRequiredPrincipal ().WillCascadeOnDelete (false);

        // 0..1 : N relation
        HasOptional (p => p.Person).WithMany (p => p.Users).HasForeignKey (p => p.PersonId);

        Property (p => p.RowVersion).IsRowVersion ();
    }
}

public class PersonMap : EntityTypeConfiguration<Person>
{
    public PersonMap ()
    {
        HasRequired (p => p.Creator).WithRequiredPrincipal ().WillCascadeOnDelete (false);
        HasRequired (p => p.ChangingUser).WithRequiredPrincipal ().WillCascadeOnDelete (false);

        // 0..1 : N relations - tried this as well - same result
        //HasOptional (p => p.Company).WithMany (p => p.Employees).HasForeignKey (p => p.CompanyId);
        //HasOptional (p => p.Facility).WithMany (p => p.People).HasForeignKey (p => p.FacilityId);

        Property (p => p.RowVersion).IsRowVersion ();
    }
}

有人可以帮我解决这个问题吗?将不胜感激!

People_Id 不在您的模型中,表示 EF 已将其插入,因为您的 Fluent 代码有误。您的用户 table 指向 Person 3 次,但您的流畅代码只告诉 EF 如何映射一个 FK (PersonId)。您需要更改其他 2 以使用 HasForeignKey 或 MapKey 指示 ForeignKey 分配(抱歉,没有现成的测试项目)。

为 UserMap 尝试这样的操作:

HasRequired(p => p.Creator).WithMany().HasForeignKey(p => p.CreatorId).WillCascadeOnDelete (false);
HasRequired(p => p.ChangingUser).WithMany().HasForeignKey(p => p.ChangingUserId).WillCascadeOnDelete (false);

我不确定您要在 PersonMap 中做什么,因为您的流畅代码引用了 2 个不在模型中的导航属性。假设您想要 2 个自引用,您将需要类似的代码。