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

时间:2019-07-12 15:25:36

标签: c# sql-server ef-core-2.2

我无法使用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”。

还有另一种方法可以在此导航属性上显式指定列名吗?

1 个答案:

答案 0 :(得分:3)

想象一下,您在UoMValue中具有显式的FK属性:

public int? UomId { get; set; }

那么您将使用:

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

指定其列名。

好吧,对于阴影属性,过程几乎相同-只是使用Property的重载代替了string propertyName方法的lambda重载:

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