【问题标题】:Entity Framework C# Introducing A Foreign Key X In Table Y May Cause Cycles OR Multiple Cascade Paths实体框架 C# 在表 Y 中引入外键 X 可能导致循环或多个级联路径
【发布时间】:2023-03-23 20:53:02
【问题描述】:

我正在开发一个 C# MVC 应用程序。我正在使用 Code First 方法对我的数据库进行建模。

我的项目有以下要求:

  1. 公司可以有很多产品
  2. 产品可以有很多广告 类型

这里是上述问题的模型类(代码优先解决方案)。

    public class Company
    {

        public Company()
        {
            this.Employees = new HashSet<ApplicationUser>();
        }

        public int ID { get; set; }

        [Required]
        public string Name { get; set; }

        public string Logo { get; set; }
        [Display(Name="Company Description")]
        public string CompanyDescription { get; set; }

        public DateTime Created { get; set; }

        public DateTime Updated { get; set; }

        public virtual ICollection<ApplicationUser> Employees { get; set; }

        public virtual ICollection<Client> Clients { get; set; }

        public ICollection<Product> Products { get; set; }
    }

    public class Product
    {
       public int ProductID { get; set; }

       public DateTime Created { get; set; }

       public DateTime Updated { get; set; }

       public string ProductName { get; set; }

       public int CompanyID { get; set; }

       public virtual Company Company { get; set; }

       public virtual ICollection<AdvertisementType> AdvertisementTypes { get; set; }
    }

    public class AdvertisementType
    {
       public int AdvertisementTypeID { get; set; }

       public int ProductID { get; set; }

       [Display(Name = "Advertisement Name")]
       public string AdvertisementTypeName { get; set; }

       public DateTime Created { get; set; }

       public DateTime Updated { get; set; }

       public virtual Product Product { get; set; }
    }

当我尝试更新数据库时,创建迁移后出现以下错误:

Introducing FOREIGN KEY constraint 'FK_dbo.AdvertisementTypes_dbo.Products_ProductID' on table 'AdvertisementTypes' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

无法创建约束或索引。查看以前的错误。

我一直在尝试解决这个问题,但找不到任何解决方案。我没有发现模型类有任何问题,我认为模型之间的关系也没有任何问题。

任何建议或帮助都会很有用。

编辑

这是表格及其关系的截图

【问题讨论】:

    标签: c# sql-server asp.net-mvc entity-framework ef-code-first


    【解决方案1】:

    如果你想避免这种情况,你需要在你的 dbContext 中将级联删除设置为 false。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    
    {
    
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    
    }
    

    您可以像使用 Company 类一样在 Product 中初始化您的 make a List()...

    public class Product
    {
       public int ProductID { get; set; }
    
    public Product()
        {
            this.AdvertisementTypes = new List<AdvertisementType>();
        }
    

    【讨论】:

    • 但是我想让广告类型属于一个产品
    猜你喜欢
    • 2019-06-06
    • 2016-03-26
    • 2013-01-07
    • 2021-04-14
    • 2015-10-26
    • 2010-10-25
    相关资源
    最近更新 更多