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

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

英孚:

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");

指定其列名。

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

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

关于c# - 如何在拥有的实体中定义关系属性的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57009944/

相关文章:

c# - 在不存在方法的类中是否需要私有(private)字段?

c# - Dapper Multiple Query Read 很慢

c# - EF Core 通过托管标识连接到 Azure SQL

sql - 简单的选择会占用大量时间

c# - 表达式类型 'System.Nullable` 1[System.Int32 ]' cannot be used for constructor parameter of type ' System.Int32'\r\n参数名称 : arguments[0]

c# - 尝试向表中添加行时无法将 Int32 转换为 null

c# - 如何从 xamarin.forms 调用平台特定页面

c# - 将视频从 pi 相机流式传输到 unity 项目

c# - 如何在以下场景中使用线程或任务模式

sql-server - 将主键添加到生产数据库