Home > Enterprise >  FK Column Name for Navigation from Owned Entity
FK Column Name for Navigation from Owned Entity

Time:02-15

Consider the following model:

class TaxRate : Entity
{
    public string Code { get; private set; }
}

class Money : ValueObject
{
    public decimal Amount { get; private set; }
}

class Price : ValueObject
{
    public Money Net { get; private set; }
    public Money? Tax { get; private set; }
    public TaxRate? TaxRate { get; private set; }
}

class Product : Entity
{
    public Price Price { get; private set; }
}

With the following configuration

class ProductMap
{
    builder.OwnsOne<Price>(p => p.Price, b =>
    {
        b.OwnsOne<Money>(p => p.Net, b =>
            b.Property(p => p.Amount).HasColumnName("Net").IsRequired());

        b.OwnsOne<Money>(p => p.Tax, b =>
            b.Property(p => p.Amount).HasColumnName("Tax").IsRequired(false));

        b.HasOne<TaxRate>(p => p.TaxRate)
            .WithMany()
            .HasForeignKey("TaxRateId");
    }).Navigation(p => p.Price).IsRequired();
}

My Product Table has following fields generated in migration:

Net = table.Column<decimal>(type: "decimal(12,2)", nullable: false),
Tax = table.Column<decimal>(type: "decimal(12,2)", nullable: true),
Price_TaxRateId = table.Column<int>(type: "int", nullable: true),

How do I get that "Price_TaxRateId" column to be created as "TaxRateId"?

CodePudding user response:

HasForeignKey specifies the FK (shadow) property name. Associated column name however is still generated by convention and adds a prefix to it.

What you need is to additionally configure explicitly the column name - as usual with HasColumnName, e.g.

b.HasOne<TaxRate>(p => p.TaxRate)
    .WithMany()
    .HasForeignKey("TaxRateId");

b.Property("TaxRateId").HasColumnName("TaxRateId"); // <--
  • Related