在表“产品”上引入FOREIGN KEY约束“ FK_Product_User_UserId”可能会导致循环或多个级联路径

时间:2019-05-26 18:22:10

标签: .net-core ef-core-2.2

我无法使用ef核心创建数据库 错误:在表“产品”上引入外键约束“ FK_Product_User_UserId”可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

这是我的产品类别

   {
       public Product()
       {
       }

       public Guid UserId { get; set; }
       public Guid CategoryId { get; set; }
       public string Name { get; set; }
       public string Description { get; set; }
       public string PhotoPath { get; set; }
       public decimal Price { get; set; }

       public Category Category { get; set; }
       public User User { get; set; }
   } 

和 这是我的用户类别

    {
        public User()
        {
            Payments = new HashSet<Payment>();
            Categories = new HashSet<Category>();
            Products = new HashSet<Product>();
        }

        public string Username { get; set; }
        public Guid Password { get; set; }

        public ICollection<Payment> Payments { get; set; }
        public ICollection<Category> Categories { get; set; }
        public ICollection<Product> Products { get; set; }
    }

其映射类

    {
        public ProductMap()
        {
        }

        public void Configure(EntityTypeBuilder<Product> builder)
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.UserId).IsRequired();
            builder.Property(x => x.CreatedDate).IsRequired();
            builder.Property(x => x.Description).HasMaxLength(500);
            builder.Property(x => x.IsActive).IsRequired();
            builder.Property(x => x.Name).HasMaxLength(500).IsRequired();
            builder.Property(x => x.PhotoPath).HasMaxLength(4000);
            builder.Property(x => x.Price).HasColumnType("decimal(10,3)").IsRequired();

            builder.HasOne(x => x.Category).WithMany(x => x.Products).HasForeignKey(x => x.CategoryId);
            builder.HasOne(x => x.User).WithMany(x => x.Products).HasForeignKey(x => x.UserId);

        }
    }

,并且我无法创建数据库,导致此帖子标题这样的错误。 我能做什么? 谢谢。

1 个答案:

答案 0 :(得分:0)

您说的是每个用户有很多类别,每个类别有很多产品,因此您必须从User类中删除此行,因为它会导致循环路径

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

并修复Configure方法的最后一行:

builder.HasOne(x => x.User).WithMany(x => x.Categories).HasForeignKey(x => x.UserId);