无法在相关表上插入重复键

时间:2017-08-29 20:57:41

标签: entity-framework foreign-keys many-to-many

我的模特拥有所有者和复合体。所有者可以拥有许多复合体,理论上复合体可以拥有多个所有者(共同所有权)。我希望能够独立创建新的复合体和所有者,因此两者都不需要另一个。但是,当我尝试添加新的复合体时,我收到此错误:

  

违反PRIMARY KEY约束'PK_dbo.Owners'。无法在对象'dbo.Owners'中插入重复键。重复键值为(fcd72b09-b1ef-4894-83de-cb4897c0c401)。   声明已经终止。

对于记录,目前有一个现有所有者(错误中提到的ID)。所有者已与另一个复合体相关联。我应该可以为这个拥有者添加一个新的复合体,但显然它不允许我这样做。

我需要更改我的模型才能适应这种情况?相关代码如下:

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.Entity<Complex>().ToTable("Complex");
        //modelBuilder.Entity<Unit>().ToTable("Unit");
        //modelBuilder.Entity<Address>().ToTable("Addresses");
        //modelBuilder.Entity<Tenant>().ToTable("Tenant");

        modelBuilder.Entity<ContactInfo>().ToTable("Contacts");

        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        modelBuilder.Entity<Complex>()
            .HasOptional(x => x.Owner)
            .WithMany(x => x.Complexes);
        modelBuilder.Entity<Unit>()
            .HasOptional(x => x.Complex)
            .WithMany(x => x.Units);
        modelBuilder.Entity<Owner>()
            .HasMany(x => x.Complexes);

        base.OnModelCreating(modelBuilder);
    }
}

所有者和复杂模型:

public class Owner
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Guid? ContactInfoId { get; set; }
    [ForeignKey("ContactInfoId")]
    public ContactInfo ContactInfo { get; set; }

    public ICollection<StaffMember> Employees { get; set; }
    public ICollection<Complex> Complexes { get; set; }

    public Owner()
    {
        this.Id = System.Guid.NewGuid();
        this.Employees = new HashSet<StaffMember>();
        this.Complexes = new HashSet<Complex>();
    }

    public void AddEmployee(StaffMember employee)
    {
        Employees.Add(employee);
    }

    public void AddComplex(Complex complex)
    {
        Complexes.Add(complex);
    }
}

public class Complex
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }

    public Guid? OwnerId { get; set; }
    [ForeignKey("OwnerId")]
    public Owner Owner { get; set; }

    public Guid? AddressId { get; set; }
    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }

    public virtual ICollection<Unit> Units { get; set; }
    public virtual ICollection<StaffMember> StaffMembers { get; set; }

    public Complex()
    {
        this.Id = System.Guid.NewGuid();
        this.Units = new HashSet<Unit>();
        this.StaffMembers = new HashSet<StaffMember>();
    }

    public void AddUnit(Unit unit)
    {
        Units.Add(unit);
    }

    public void AddStaff(StaffMember staffMember)
    {
        StaffMembers.Add(staffMember);
    }
}

1 个答案:

答案 0 :(得分:0)

您的实体设置不正确。在Complex对象中,您声明它只有1个所有者,因此您将其设置为一对多而不是多对多。如果将其设置为集合而不是对象,EF将为您处理多对多的表