EF表中的核心一对多自关系



对于下列型号:

public sealed class Foo
{
public Guid Id { get; set; }
public List<Foo> Foos { get; set; }
}

可不可以这样写:

public sealed class FooEntityTypeConfiuration : IEntityTypeConfiguration<Foo>
{
public void Configure(EntityTypeBuilder<Foo> builder)
{
builder.ToTable("foos");
builder.HasKey(_ => _.Id);
builder
.HasOne()
.WithMany(_ => _.Foos)
.HasForeignKey(_ => _.Id)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired(true);
}
}
单个中创建一对多自关系postgresql表EF Core?谢谢你。

So-o-o -o…答案是:

  1. 更改模型
public sealed class Foo
{
public Guid Id { get; set; }
public Guid? ParentFooId { get; set; }
public Foo ParentFoo { get; set; }
public List<Foo> Foos { get; set; }
}
  1. ChangeIEntityTypeConfiguration.
public sealed class FooEntityTypeConfiuration : IEntityTypeConfiguration<Foo>
{
public void Configure(EntityTypeBuilder<Foo> builder)
{
builder.ToTable("foos");
builder.HasKey(_ => _.Id);
builder
.HasOne(_ => _.ParentFoo)
.WithMany(_ => _.Foos)
.HasForeignKey(_ => _.ParentFooId)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired(false);
builder.HasIndex(_ => _.ParentFooId);
}
}

在迁移中你会得到这样的东西

migrationBuilder.CreateTable(
name: "foos",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
ParentFooId = table.Column<Guid>(type: "uuid", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_foos", x => x.Id);
table.ForeignKey(
name: "FK_foos_foos_ParentFooId",
column: x => x.ParentFooId,
principalTable: "foos",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_foos_ParentFooId",
table: "foos",
column: "ParentFooId");

相关内容

  • 没有找到相关文章

最新更新