Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First - Invalid column name Discriminator

Two Classes in codefirst

public partial class BaseEntity 
{
    public int ID { get; set; }
}

public partial class Fund : BaseEntity
{
   public int Name { get; set; }
}
public partial class InvestorFund : BaseEntity 
{
  public int FundID { get; set; }
}

Mapping Classes

this.Property(t => t.ID).HasColumnName("FundID");

My Code First Join SQL Query

from fund in context.Funds

join investorFund in context.InvestorFunds on fund.ID equals investorFund.FundID

Throws an Invalid column name Discriminator

like image 619
karthi Avatar asked Sep 14 '26 16:09

karthi


1 Answers

You need to tell Code First how these classes relate to tables. There are three options:

  • Table per type (TPT) would mean the fields defined on Fund and InvestorFund would go into their own tables and properties defined on BaseEntity would go to a table named BaseEntity. Querying would be slower as each entity now has to combine the fields from multiple tables.

    modelBuilder.Entity<Fund>().ToTable("Funds");
    modelBuilder.Entity<InvestorFund>().ToTable("InvestorFunds");
    
  • Table per heirarchy (TPH) would mean that Fund, InvestorFund and BaseEntity properties would all be merged into a single table named BaseEntity and an extra field would be required to indicate which row is which type. This extra field is called the discriminator.

    modelBuilder.Entity<BaseEntity>()
      .Map<Fund>(m => m.Requires("Discriminator").HasValue("F"))
      .Map<InvestorFund>(m => m.Requires("Discriminator").HasValue("I"));
    
  • Table per concrete type (TPC) would mean that Fund and InvestorFund each have their own table which would also include any fields needed for their base classes.

    modelBuilder.Entity<Fund>().Map(m => {
                  m.MapInheritedProperties();
                  m.ToTable("Funds"); 
    }); 
    modelBuilder.Entity<InvestorFund>().Map(m => {
                  m.MapInheritedProperties();
                  m.ToTable("InvestorFunds"); 
    });
    
like image 86
DamienG Avatar answered Sep 21 '26 23:09

DamienG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!