【问题标题】:Renaming Foreign Key for Value Object's Entity in Entity Framework Core在 Entity Framework Core 中为值对象的实体重命名外键
【发布时间】:2021-11-13 17:43:39
【问题描述】:

在使用带有 Entity Framework Core 的值对象内的实体时,我遇到了列命名问题。 EF 想要将值对象的实体的外键命名为长而丑陋的名称。例如。 PropertyName_ForeignKeyID。我想要的是使用 Fluent API 控制 db 列字段的名称。

如果我有一个名为 Measurement 的值对象,并且它具有一个名为 UnitOfMeasure 的实体的属性,则关系可以正常工作,但列命名非常难看。

以下是示例模型

public class EntityA
{
    public int Id { get; set; }
    public Measurement VO { get; set; }
}

public class Measurement
{
    public double Value { get; set; }
    public UnitOfMeasure UOM { get; set; }
}

// Second Entity
public class UnitOfMeasure
{
    public int Id { get; set; }
    public string Name { get; set; }
}

以及我尝试过的配置

var withEntity = modelBuilder.Entity<EntityA>().OwnsOne(t => t.VO);

// This works fine
withEntity.Property(e => e.Value).HasColumnName("WithEntityValue");

// Tried this but the results of the column name is VO_WithEntityValueUOMId
withEntity.HasOne(e => e.UOM).WithMany().HasForeignKey("WithEntityValueUOMId");

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    HasForeignKey 指定(影子)属性 名称。常规列名称与属性名称相同,但是对于拥有的实体类型,它包括所有者属性名称(类似于其他属性)。

    因此,您需要指定类似于“工作”示例的 名称。例如知道在这种情况下常规的影子 FK property 名称是UOMId,它可以设置如下

    withEntity.Property("UOMId").HasColumnName("WithEntityValueOUMId");
    

    或者您可以同时更改 FK 属性和列名

    withEntity.HasOne(e => e.UOM).WithMany().HasForeignKey("WithEntityValueUOMId");
    withEntity.Property("WithEntityValueUOMId").HasColumnName("WithEntityValueUOMId");
    

    在这两种情况下,您都需要Property(FKPropertyName).HasColumnName(FKColumnName)FKColumnName 是所需的名称,但 FKPropertyName 应该是已知的或使用 HasForeignKey 显式设置,如第二个示例所示。在这两种情况下都可以通过从 EF Core 元数据 API 中提取(并实际设置它)来避免这种情况,例如

    
    var foreignKey = withEntity.HasOne(e => e.UOM).WithMany().Metadata;
    // with metadata API
    foreignKey.Properties[0].SetColumnName("WithEntityValueUOMId");
    // or if you prefer fluent API, even though I see no benefit of using it in this particular case
    withEntity.Property(foreignKey.Properties[0].Name).HasColumnName("WithEntityValueUOMId");
    

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 2018-09-22
      • 1970-01-01
      • 2022-01-19
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      相关资源
      最近更新 更多