There is a ton of info on setting the behavior for delete actions for foreign key relationships in Entity Framework Core, however, I have found nearly zero details on how to specify the "On Update Cascade" constraint of a foreign key.
The closest I have found is this migrations related Microsoft document.
public void Configure(EntityTypeBuilder<Something> builder)
{
builder
.HasOne(s => s.Thing)
.WithMany(t => t.Somethings)
.HasForeignKey(s => s.ThingId)
--> Like Delete behavior, how to set update behavior?
.OnDelete(DeleteBehavior.Cascade);
}
How can this be done with the Fluent API?
Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.
The EF Core in-memory database does not currently support cascade deletes in the database.
ON DELETE CASCADE : if a row of the referenced table is deleted, then all matching rows in the referencing table are deleted. ON DELETE SET NULL : if a row of the referenced table is deleted, then all referencing columns in all matching rows of the referencing table to be set to null.
Update: This still does not fix the underlying issue of when you "context.SaveChanges();" it will still throw an error. You have to null the record in the Database and then repopulate it.
I have been looking for the Exact same thing and I found a work around. As far as I can tell you cannot do this in the Fluent API yet. What you can do is add it into the migration manually.
See below for reference
migrationBuilder.CreateTable(
name: "AgencyMembers",
columns: table => new
{
ApplicationUserId = table.Column<string>(maxLength: 450, nullable: false),
AgencyId = table.Column<int>(nullable: false),
AgencyName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AgencyMembers", x => new { x.ApplicationUserId, x.AgencyId });
table.ForeignKey(
name: "FK_AgencyMembers_AspNetUsers_ApplicationUserId",
column: x => x.ApplicationUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
***onUpdate: ReferentialAction.Cascade,***
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AgencyMembers_Agencies_AgencyId_AgencyName",
columns: x => new { x.AgencyId, x.AgencyName },
principalTable: "Agencies",
principalColumns: new[] { "AgencyId", "AgencyName" },
***onUpdate: ReferentialAction.Cascade,***
onDelete: ReferentialAction.Cascade);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With