gpt4 book ai didi

c# - EF核心: Using ID as Primary key and foreign key at same time

转载 作者:行者123 更新时间:2023-12-01 19:18:02 24 4
gpt4 key购买 nike

我有两个实体,ProspectPerson ,我想做的是使用 Prospect.ID作为 Prospect 上的主键表并作为 PersonID 的外键,我的想法是对两个实体使用相同的 ID,而不需要 PersonID在我的Prospect上实体。当潜在客户保存在数据库中时,它会尝试保存 PersonID即使我的 Prospect 上没有此属性实体,我想知道EF core是否支持这种关系。

这是我在模型构建器上得到的内容:

modelBuilder.Entity<ProspectDto>(builder => { builder.ToTable("Prospects"); builder.HasKey(prospect => prospect.ID); });

modelBuilder.Entity<PersonDto>(builder => { builder.HasOne(p => p.Prospect).WithOne().HasForeignKey<ProspectDto>(pe => pe.ID); });

这是在数据库上执行的内容:

INSERT INTO [Prospects] ([ID], [PersonID]) VALUES (@p421, @p422)

PersonDto :

public class PersonDto : DtoBase
{
public PersonDto()
{

}

public ProspectDto Prospect { get; set; }
}

ProspectDto :

public class ProspectDto : DtoBase
{
public ProspectDto()
{

}

public PersonDto Person { get; set; } = new PersonDto();
}

DtoBase :

public abstract class DtoBase
{
public Guid ID { get; protected set; }
}

谢谢。

最佳答案

仅使用属性,不使用 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<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Persons", x => x.ID);
});

migrationBuilder.CreateTable(
name: "Prospects",
columns: table => new
{
ID = table.Column<Guid>(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);
});
}

看起来非常接近您所需要的。

关于c# - EF核心: Using ID as Primary key and foreign key at same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41261738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com