2017-08-28 52 views
1

錯誤:引入表'TenantUnits'上的FOREIGN KEY約束'FK_dbo.TenantUnits_dbo.Units_Unit_Id'可能會導致循環或多個級聯路徑。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。實體框架多對多的級聯約束

我知道這個錯誤與模型中關係的性質有關,但我很困惑以至於無法對其進行分類。我在繞過級聯以及涉及我模型的多對多關係方面遇到了困難。

模型如下:

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

    public Guid AddressId { get; set; } 

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

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

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

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

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

    public Guid ComplexId { get; set; } 
    [ForeignKey("ComplexId")] 
    public virtual Complex Complex { get; set; } 

    public virtual ICollection<Tenant> Tenants { get; set; } 

    public Unit() 
    { 
     this.Id = System.Guid.NewGuid(); 
     this.Tenants = new HashSet<Tenant>(); 
    } 

    public void AddTenant(Tenant tenant) 
    { 
     Tenants.Add(tenant); 
    } 
} 

public class Tenant 
{ 
    [Key] 
    public Guid Id { get; set; } 
    public string UserId { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    public Guid ContactInfoId { get; set; } 
    [ForeignKey("ContactInfoId")] 
    public ContactInfo ContactInfo { get; set; } 

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

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

public class Address 
{ 
    [Key] 
    public Guid Id { get; set; } 
    public string Address1 { get; set; } 
    public string Address2 { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string Zip { get; set; } 

    public Address() 
    { 
     this.Id = System.Guid.NewGuid(); 
    } 
} 

public class ContactInfo 
{ 
    [Key] 
    public Guid Id { get; set; } 

    public Guid AddressId { get; set; } 
    [ForeignKey("AddressId")] 
    public Address Address { get; set; } 
    public string Phone1 { get; set; } 
    public string Phone2 { get; set; } 
    public string Email { get; set; } 

    public ContactInfo() 
    { 
     this.Id = System.Guid.NewGuid(); 
    } 
} 

編輯:我加入modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); 解決了錯誤,但我還是不完全瞭解的影響和/或它是如何工作的 - 或者,如果這是連我需要使用。

回答

0

ICollection用於定義實體之間的一對多或多對多關係。在你的「複雜」類中,你已經定義了一個「單元」的ICollection。但是,Complex類中沒有定義映射到Unit實體主鍵的外鍵屬性「UnitId」。實體框架將Complex類的「Id」映射到Unit類的「Id」。 (假設:單位,綜合體和租戶的身份不同)。這可能是錯誤背後的原因。定義「UnitId」屬性並將外鍵屬性添加到「單元」集合中。同樣,修復你的Tenant和Unit類。