2017-08-28 49 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类。