Closed as duplicate of#27971
Description
Problem
I have a database with the Main
and Details
tables. The Blog
table depends on Main
. All this is reflected in the EF entities.
I want to combine the Main
and Details
entities without changing the database structure. I use SplitToTable
for this. But after creating the migration, the foreign key: FK_Blog_Main_MainId
is deleted and FK_Blog_Details_MainId
is created instead.
Code
https://github.com/AndreqGav/efcore.example.split-to-table
At first, the entities look like this:
public class Main
{
public int Id { get; set; }
public string? Name { get; set; }
public virtual Details? Details { get; set; }
public Blog? Blog { get; set; }
}
public class Details
{
public int Id { get; set; }
public string? Description { get; set; }
}
public class Blog
{
public int Id { get; set; }
public string? Name { get; set; }
public int? MainId { get; set; }
public virtual Main? Main { get; set; }
}
EF Configuration:
modelBuilder.Entity<Main>(builder =>
{
builder.HasOne(e => e.Details).WithOne()
.HasForeignKey<Details>(e => e.Id);
});
modelBuilder.Entity<Details>(builder =>
{
builder.HasKey(e => e.Id);
});
modelBuilder.Entity<Blog>(builder =>
{
builder.HasKey(e => e.Id);
builder.HasOne(e => e.Main).WithOne(e => e.Blog)
.OnDelete(DeleteBehavior.Cascade)
.HasForeignKey<Blog>(e => e.MainId);
});
After using SplitToTable
The Details
class has been deleted
public class Main
{
public int Id { get; set; }
public string? Name { get; set; }
// public virtual Details? Details { get; set; }
public Blog? Blog { get; set; }
#region Details
public string? Description { get; set; }
#endregion
}
EF Configuration:
modelBuilder.Entity<Main>(builder =>
{
// builder.HasOne(e => e.Details).WithOne()
// .HasForeignKey<Details>(e => e.Id);
builder.SplitToTable("Details", tb =>
{
tb.Property(e => e.Description);
});
});
// modelBuilder.Entity<Details>(builder =>
// {
// builder.HasKey(e => e.Id);
// });
modelBuilder.Entity<Blog>(builder =>
{
builder.HasKey(e => e.Id);
builder.HasOne(e => e.Main).WithOne(e => e.Blog)
.OnDelete(DeleteBehavior.Cascade)
.HasForeignKey<Blog>(e => e.MainId);
});
After migration
migrationBuilder.DropForeignKey(
name: "FK_Blog_Main_MainId",
table: "Blog");
migrationBuilder.AddForeignKey(
name: "FK_Blog_Details_MainId",
table: "Blog",
column: "MainId",
principalTable: "Details",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
Include provider and version information
EF Core version:
Database provider: (e.g. Microsoft.EntityFrameworkCore.PostgreSQL)
Target framework: (e.g. .NET 9.0)