【问题标题】:Setting custom foreign key column name with private field with EFCore使用 EFCore 使用私有字段设置自定义外键列名称
【发布时间】:2019-08-27 00:33:36
【问题描述】:

我有以下数据模型:

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; }
}

这很好用,根据我的期望,我有一个包含IdBarIdFoo 表。从数据库中读取Foo 时,我的私有字段BarIdBar 属性也正确实现。

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

这可能吗?


我尝试重命名 Foo 类中的字段并在 EntityTypeConfiguration 中指定我的(现在非常规命名的)外键 _barId

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

但这导致 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);
    });

【问题讨论】:

    标签: entity-framework-core


    【解决方案1】:

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

    所以下面一行:

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

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

    您使用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 查询中访问它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-24
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2011-06-17
      • 2020-11-03
      • 2013-11-22
      • 2011-05-17
      相关资源
      最近更新 更多