简体   繁体   中英

Error when creating the table : Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints

I get this error:

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

What is the problem in my code?

    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; }
    }

Thank you for answering. I solved the issue by changing a couple of things in my code.

This is my solution code(you can see the changes):

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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM