如何在拥有的实体中定义关系 属性 的名称

How to define the name of a Relationship property inside an Owned Entity

我无法使用 EF Core (2.2)

在拥有的实体内为关系定义自定义名称 属性

这是我的设置:

SQL(为简单起见省略了其余列):

CREATE TABLE Forecast (..., Quantity DECIMAL(25,15), UoMId int, ...)

C#

public abstract class Entity
{
    public int Id { get; protected set; }
}

public class Forecast : Entity
{
    ...
    public UoMValue Size { get; set; }
    ...
}

public class UoMValue
{
    public BalanceUoM UoM { get; private set; }
    public decimal Value { get; private set; }
}

public class BalanceUoM : Entity
{
    private BalanceUoM() {}
    public BalanceUoM(string unit)
    {
        Unit = unit;
    }

    public string Unit { get; private set;}
    public string Description { get; set; }
}

EF:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<Forecast>(entity =>
     {
            entity.OwnsOne(x => x.Size, builder =>
            {
                builder.Property(e => e.Value)
                    .HasColumnName("Quantity")
                    .HasColumnType("decimal(25, 15)");

                //following line fails because EF is looking for "Size_UoMId"
                builder.HasOne(e => e.UoM).WithMany();
            });
     });
}

这里的问题是我不能像使用另一个 属性 那样使用 .HasColumnName("UomId")。 添加 .HasForeignKey("UomId") 似乎没有做任何事情,它仍然在寻找相同的 属性 名称 "Size_UoMId".

是否有另一种方法可以在此导航中明确指定列名 属性?

假设您在 UoMValue 中有明确的 FK 属性:

public int? UomId { get; set; }

那么你会使用:

builder.Property(e => e.UomId)
    .HasColumnName("UomId");

指定其列名。

嗯,对于 shadow 属性,过程几乎相同 - 只是不是 Property 方法的 lambda 重载,而是使用 string propertyName:[=16= 的重载]

builder.Property<int?>("UomId")
    .HasColumnName("UomId");