gpt4 book ai didi

entity-framework-core - 使用 EFCore 使用私有(private)字段设置自定义外键列名称

转载 作者:行者123 更新时间:2023-12-04 03:08:16 25 4
gpt4 key购买 nike

我有以下数据模型:

public class Foo
{
public Foo(int barId)
{
BarId = barId;
}

private int BarId;
public Bar Bar { get; private set; }
}

public class FooTypeConfig : IEntityTypeConfiguration<Foo>
{
public void Configure(EntityTypeBuilder<Foo> builder)
{
builder.HasOne(x => x.Bar)
.WithMany()
.HasForeignKey("BarId");
}
}

public class Bar
{
public int Id { get; private set; }
}

这很好用,根据我的期望,我有一个 Foo包含 Id 的表格和 BarId .我的私有(private)领域 BarId和我的 Bar读取 Foo 时,属性也正确实现从数据库。

问题是我想找到一种方法来命名我的私有(private)字段,并为我的数据库列选择不同的名称。我想为我的属性(property)命名 _barId仍然选择 BarId作为我数据库中的列名。

这可能吗?

我尝试在我的 Foo 中重命名该字段类并指定我的(现在非常规命名的)外键 _barId在我的 EntityTypeConfiguration
builder.HasOne(x => x.Bar).WithMany().HasForeignKey("_barId");

但这导致 EF 仍然生成 BarId列,不使用它作为 Bar 的外键 table ...

migrationBuilder.CreateTable(
name: "Foos",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BarId = table.Column<int>(nullable: true),
_barId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Foos", x => x.Id);
table.ForeignKey(
name: "FK_Foos_Bars__barId",
column: x => x._barId,
principalTable: "Bars",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});

Foo table structure

最佳答案

首先,EF 将数据库列和 FK 映射到实体属性,而不是字段。这些属性可以是真实的,也可以像您的情况一样 - shadow .

所以下面一行:

builder.HasOne(x => x.Bar).WithMany().HasForeignKey("BarId");

映射 Bar -> Foo FK 与 Foo 的关系名为 BarId 的影子属性并且应该保持原样。

您使用 Property方法来配置属性类型、支持字段、列名、类型和其他属性。例如:
builder.Property<int>("BarId") // or int? etc.
.HasField("_barId")
.HasColumnName("BarId"); // or BazId or whatever you like

只需确保在定义它和指定 FK 时使用一个相同的属性名称。您也可以使用 Entry(entity).Property(propertyName)获取/设置值,将其标记为已修改等以及 EF.Property(entity, propertyName ) 在 LINQ to Entities 查询中访问它。

关于entity-framework-core - 使用 EFCore 使用私有(private)字段设置自定义外键列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47622953/

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