I have the following code in an, what looks like a futile, attempt to configure the OnDelete
behaviour for foreign keys:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Contact>()
.HasOne(e => e.Gender)
.WithMany()
.HasForeignKey(e => e.GenderId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Contact>()
.HasOne(e => e.Title)
.WithMany()
.HasForeignKey(e => e.TitleId)
.OnDelete(DeleteBehavior.Restrict);
}
Yet when I generate the first migration, that creates this and another two tables, it creates constraints for Contact
as follows:
constraints: table =>
{
table.PrimaryKey("PK_Contact", x => x.Id);
table.ForeignKey(
name: "FK_Contact_Gender_GenderId",
column: x => x.GenderId,
principalTable: "Gender",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
table.ForeignKey(
name: "FK_Contact_Title_TitleId",
column: x => x.TitleId,
principalTable: "Title",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
Where the blazes does it get SetNull
, on a non-nullable column, GenderId
? Cascade
is maybe a default, having ignored my configuration.
As suggested by @bricelam, I submitted an issue and got a correct response in less than 24 hours. Microsoft's Smit Patel advised:
In your
project.json
you have reference toMicrosoft.EntityFrameworkCore.Commands
which was deprecated a while ago and should be removed.
I removed it and the re-generated migration now has the correct onDelete
values for both FKs.