使用EFCore使用私有字段设置自定义外键列名称

Sch*_*out 5 entity-framework-core

我有以下数据模型:

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; }
}
Run Code Online (Sandbox Code Playgroud)

效果很好,根据我的期望,我有一个Foo包含Id和的表BarId。从数据库中读取时,我的私有字段BarId和我的Bar财产也已正确实现Foo

问题是我想找到一种方式来命名我的私有字段,并为我的数据库列选择一个不同的名称。我想命名我的财产_barId,但仍选择BarId数据库中的列名。

这可能吗?


我试图重命名我的Foo班级中的字段,并_barId在我的我的外键中指定我的(现在是非常规名称)外键EntityTypeConfiguration

builder.HasOne(x => x.Bar).WithMany().HasForeignKey("_barId");
Run Code Online (Sandbox Code Playgroud)

但这导致EF仍然生成一BarId列,而没有将其用作Bar表的外键...

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);
    });
Run Code Online (Sandbox Code Playgroud)

Foo表结构

Iva*_*oev 5

首先,EF将数据库列和FK映射到实体属性,而不是字段。这些属性可以是真实的,也可以是阴影的

所以下面这行:

builder.HasOne(x => x.Bar).WithMany().HasForeignKey("BarId");
Run Code Online (Sandbox Code Playgroud)

Bar-> Foo关系FK 映射到Foo名为BarId并且应保持原样的shadow属性。

您可以使用该Property方法配置属性类型,后备字段,列名,类型和其他属性。例如:

builder.Property<int>("BarId") // or int? etc.
    .HasField("_barId")
    .HasColumnName("BarId"); // or BazId or whatever you like 
Run Code Online (Sandbox Code Playgroud)

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