仅使用属性,不使用FluentAPI:
public abstract class DtoBase
{
[Key]
public Guid ID { get; protected set; }
}
public class PersonDto : DtoBase
{
[InverseProperty("Person")]
public ProspectDto Prospect { get; set; }
}
public class ProspectDto : DtoBase
{
[ForeignKey("ID")] // "magic" is here
public PersonDto Person { get; set; } = new PersonDto();
}
我不知道FluentAPI中 ForeignKey 的等价物 . 所有其他(Key和InverseProperty)都是可配置的,但为什么要使用两种方法而不是一种 .
上面的代码生成以下迁移代码:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Persons",
columns: table => new
{
ID = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Persons", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Prospects",
columns: table => new
{
ID = table.Column(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Prospects", x => x.ID);
table.ForeignKey(
name: "FK_Prospects_Persons_ID",
column: x => x.ID,
principalTable: "Persons",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
}
看起来非常接近您的需求 .