【问题标题】:Error when creating the table : Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints创建表时出错:指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束
【发布时间】:2021-05-29 18:10:23
【问题描述】:

我收到此错误:

引入 FOREIGN KEY 约束可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。

我的代码有什么问题?

    public class AppUserMap : IEntityTypeConfiguration<AppUser>
    {
        public void Configure(EntityTypeBuilder<AppUser> builder)
        {
            builder.Property(m => m.Name).HasMaxLength(50).IsRequired(true);
            builder.HasMany(m => m.Essays).WithOne(m => m.AppUser).HasForeignKey(m => m.AppUserId);
        }
    }
    public class AppRoleMap : IEntityTypeConfiguration<AppRole>
    {
        public void Configure(EntityTypeBuilder<AppRole> builder)
        {
            builder.HasKey(m => m.Id);
            builder.HasMany(m => m.AppUsers).WithOne(m => m.AppRole).HasForeignKey(m => m.AppRoleId).OnDelete(DeleteBehavior.NoAction);
        }
    }
    public class AppRole : IdentityRole<int>, ITable
    {
        public List<AppUser> AppUsers { get; set; }
    }
    public class AppUser : IdentityUser<int>, ITable
    {
        public string Name { get; set; }
        public string Picture { get; set; } = "default.png";
        #nullable enable
        public string? AppUserRole { get; set; }
        #nullable disable
        public bool Ban { get; set; } = false;

        public List<Essay> Essays { get; set; }

        public AppRole AppRole { get; set; }
        public int AppRoleId { get; set; }
    }

【问题讨论】:

  • 您能否发布导致错误的迁移文件?
  • 我们需要知道错误发生的地点/时间。

标签: asp.net .net asp.net-core entity-framework-core foreign-keys


【解决方案1】:

感谢您的回答。我通过更改代码中的一些内容解决了这个问题。

这是我的解决方案代码(你可以看到更改):

public class AppUser : IdentityUser<int>, ITable
    {
        public string Name { get; set; }
        public string Picture { get; set; } = "default.png";
        public bool Ban { get; set; } = false;

        public List<Essay> Essays { get; set; }

#nullable enable
        public AppRole? AppRole { get; set; }
        public int? AppRoleId { get; set; }
#nullable disable
    }


public class AppRoleMap : IEntityTypeConfiguration<AppRole>
    {
        public void Configure(EntityTypeBuilder<AppRole> builder)
        {
            builder.HasKey(m => m.Id);
            builder.HasMany(m => m.AppUsers).WithOne(m => m.AppRole).HasForeignKey(m => m.AppRoleId).OnDelete(DeleteBehavior.SetNull);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 2021-05-08
    • 1970-01-01
    • 2023-01-24
    • 2012-10-03
    • 2013-08-01
    相关资源
    最近更新 更多