I have a table in an existing database that looks something like this:
PK
FK
Col1
Col2
Col3
Col4
Col5
I need to get it into a class hierarchy like this:
public abstract class BaseClass : Entity
{
public int PK {get; set;}
public string Col1 {get; set;}
}
public class Child1 : BaseClass
{
public string Col2 {get; set;}
public string Col3 {get; set;}
}
public class Child2 : BaseClass
{
public string Col4 {get; set;}
public string Col5 {get; set;}
}
I am currently using the Fluent API to configure the entities like so:
public abstract class BaseClassConfig<TEntity> : EntityTypeConfiguration<TEntity> where TEntity : Entity
{
public BaseClassConfig()
{
ToTable("TheTableName");
HasKey(x => x.Id);
Property(x => x.Col1).HasColumnName("SomeName");
}
}
public class Child1Config : BaseClassConfig<Child1>
{
public Child1Config()
{
Property(x => x.Col2).HasColumnName("SomeName");
Property(x => x.Col3).HasColumnName("SomeName");
}
}
public class Child2Config : BaseClassConfig<Child2>
{
public Child2Config()
{
Property(x => x.Col4).HasColumnName("SomeName");
Property(x => x.Col5).HasColumnName("SomeName");
}
}
When I added these to the context the inherits from DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Child1Config());
modelBuilder.Configurations.Add(new Child2Config());
}
I get the following error:
The entity types 'Child1' and 'Child2' cannot share table 'TheTableName' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
I had a look at this article: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application
But it does not really talk about using the fluent api to configure the types, rather directly adding them to the context via DbSet<>.
How do I setup a single table to map to different classes through a base class using the fluent api?
BaseClasshas common properties to bothChild1andChild2, whereas each of them have their own properties not related to each other. It is inheritance in the simplest form. But in this case the existing schema has all the properties stored in the same table.