Add-Migration automatically set 'onDelete: ReferentialAction.Restrict);'

Viewed 80

in ASP.NET Core EF I have two related tables. One with genders (Male/Female) one with Names.

Model/Personal.cs

namespace Employees.Models
{
    public class Personal
    {
        [Key]
        public int GenderID { get; set; }

        [StringLength(30)]
        public string Gender { get; set; }

    }
}

Model/Name.cs

namespace Employees.Models
{
    public class Name
    {
        [Key]
        public int NameID { get; set; }

        [StringLength(30)]
        public string FirstName { get; set; }

        [StringLength(30)]
        public string LastName { get; set; }
        
        public int PersonalGenderID { get; set; }
    }
}

Data/MyContext.cs

namespace Employees.Data
{
    public class MyContext : DbContext
    {
        public MyContext(DbContextOptions<MyContext> options) : base(options)
        {

        }
       
        public DbSet<Personal> Personals { get; set; }
        public DbSet<Name> Names { get; set; }

    }
}

After the “Add-Migration InitialCreate” command the table designer part shows this.

Migrations/..._InitialCreate.cs

constraints: table =>
{
    table.PrimaryKey("PK_Names", x => x.NameID);
    table.ForeignKey(
        name: "FK_Names_Personals_PersonalGenderID",
        column: x => x.PersonalGender,
        principalTable: "Personals",
        principalColumn: "GenderID",
        onDelete: ReferentialAction.Cascade);
});

I always have to replace the onDelete: ReferentialAction.Cascade); line to onDelete: ReferentialAction.Restrict);

What do I have to change to make the Add-Migration command automatically sets the onDelete to Restrict

1 Answers

Never mind. Found it. If you have the same problem.

In Data/MyContext.cs add

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    foreach (var foreignKey in modelBuilder.Model.GetEntityTypes()
        .SelectMany(e => e.GetForeignKeys()))
    {
        foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
    }
}
Related