Panos
Panos

Reputation: 55

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

I am unable to define a custom name for a relationship property inside an owned entity using EF Core (2.2)

This is my setup:

SQL (ommitted rest of columns for simplicity):

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

The problem here is that I cannot use .HasColumnName("UomId") like I did for the other property. Adding .HasForeignKey("UomId") does not seem to be doing anything, it still looks for the same property name "Size_UoMId".

Is there another way to specify the column name explicitly on this navigation property?

Upvotes: 1

Views: 57

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205769

Imagine you have explicit FK property in UoMValue:

public int? UomId { get; set; }

Then you would have used:

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

to specify its column name.

Well, for shadow property the procedure is pretty much the same - just instead of lambda overload of Property method you would use the overload with string propertyName:

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

Upvotes: 3

Related Questions