asp.net-mvc - 引入 FOREIGN KEY 约束可能会导致循环或多条级联路径

标签 asp.net-mvc entity-framework-6

我的 MVC 项目中有以下实体(代码优先方法) 我想知道我收到以下错误的原因是什么

Introducing FOREIGN KEY constraint 'FK_dbo.VendorDetails_dbo.States_StateID' on table 'VendorDetails' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

我只是想知道哪些表获得多个级联路径,任何图表都会有效,以及我应该使用像这样的流畅 API 编写什么: modelBuilder.Entity<...>() .HasRequired(...) .WithMany(...) .HasForeignKey(...) .WillCascadeOnDelete(false);

public class VendorDetails
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int VendorID { get; set; }        
    [MaxLength(60)]
    public string VendorName { get; set; }        

    public int VendorTypeID { get; set; }
    public int CountryID { get; set; }
    public int StateID { get; set; }        

    [NotMapped]
    public string CountryName { get; set; }
    [NotMapped]
    public string StateName { get; set; }
    [NotMapped]
    public string VendorTypeName { get; set; }

    public virtual Country Country { get; set; }
    public virtual State State { get; set; }
    public virtual VendorType VendorType { get; set; }
}

public class VendorType
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int VendorTypeID { get; set; }                

    public string VendorTypeName { get; set; }

    public virtual ICollection<VendorDetails> Vendors { get; set; }
 }


public class Country
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CountryID { get; set; }
    public string CountryName { get; set; }

    public virtual ICollection<State> States { get; set; }
}

public class State
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StateID { get; set; }
    public string StateName { get; set; }

    public int CountryID { get; set; }
    public virtual Country Country { get; set; }
}

最佳答案

您得到此信息是因为“国家/地区”有一个到“州”的链接,而“VendorDetails”有一个到“国家/地区”和“州”的链接。这在 VendorDetails 和 State 之间提供了多条路径 - 一条通过 Country,一条直接。

我将禁用从 VendorDetails 链接到状态的级联删除:

modelBuilder
    .Entity<VendorDetails>()
        .HasOptional(e => e.State)
        .WithMany()
        .WillCascadeOnDelete(false);

关于asp.net-mvc - 引入 FOREIGN KEY 约束可能会导致循环或多条级联路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29937651/

相关文章:

asp.net-mvc - 在 MVC3 中使用带有自定义成员资格提供程序的 microsoft-mvc-helpers 包时出现问题

c# - 正则表达式:相对 URL 的绝对 URL (C#)

c# - 在 EPPlus 中调用 LoadFromCollection 时忽略属性

c# - "Attaching an entity of type T failed because another entity of the same type already has the same primary key value"

jquery - MVC jqgrid最佳实现

asp.net-mvc - Azure云服务部署: The type or namespace name 'Helpers' does not exist

c# - 读取 View MVC 中的 Session 值

c# - Entity Framework - 错误地执行 2 个选择语句而不是连接

c# - 为什么编译器要求在用户界面项目中引用 Entity Framework ?

c# - 将 Entity Framework 调用绑定(bind)到一个公共(public)参数,例如 UserId