我已经为三个 1:many 关系指定了级联删除,但它没有在数据库中设置它。以下是 Event 由 Campaign、County 或 State“拥有”的类。三者中仅一者。我在这里只展示活动,但其他人也有相同的代码。
public class Event
{
public required User Owner { get; set; }
public Campaign? Campaign { get; set; }
public County? County { get; set; }
public State? State { get; set; }
// lots of other props...
}
public class Campaign
{
public ICollection<Event> Events { get; set; }
// lots of other props...
}
public class CampaignConfiguration : IEntityTypeConfiguration<Campaign>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<Campaign> builder)
{
builder.HasIndex(new[] { "Name", "StateId" }).IsUnique();
builder.HasIndex("StateId");
builder.HasMany(x => x.Events)
.WithOne(x => x.Campaign).OnDelete(DeleteBehavior.ClientCascade);
}
}
并且在 migration.cs 中(注意用户有一个事件集合,因此它被设置为级联删除)
migrationBuilder.CreateTable(
name: "Events",
columns: table => new
{
// all the columns
},
constraints: table =>
{
table.PrimaryKey("PK_Events", x => x.Id);
table.ForeignKey(
name: "FK_Events_Campaigns_CampaignId",
column: x => x.CampaignId,
principalTable: "Campaigns",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Events_Counties_CountyId",
column: x => x.CountyId,
principalTable: "Counties",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Events_States_StateId",
column: x => x.StateId,
principalTable: "States",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Events_Users_OwnerId",
column: x => x.OwnerId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
为什么不把这些设置成级联删除?