I have two tables in a legacy database (which I cannot modify) with data as follows:
Table1 has a composite primary key (Code, Abbrev), but Abbrev is also used as a discriminator (see below). Table2 has two foreign key columns (CodeA, CodeB), both referencing the same field Code in Table1. There are duplicates in the Table1.Code field.
I would like to use table-per-hierarchy approach with Entity framework 6. So, I created the following model classes:
[Table("Table1")]
public class MyBaseClass
{
[Key]
public string Code { get; set; }
}
public class MyBaseClassA : MyBaseClass
{
}
public class MyBaseClassB: MyBaseClass
{
}
[Table("Table2")]
public class SubClass
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("MyBaseClassA")]
public string CodeA { get; set; }
public virtual MyBaseClassA ClassA { get; set; }
[Required]
[ForeignKey("MyBaseClassB")]
public string CodeA { get; set; }
public virtual MyBaseClassB ClassB { get; set; }
}
I defined table-per-hierarchy in my DataContext : DbContext class as follows:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyBaseClass>().Map<MyBaseClassA>(m => m.Requires("Abbrev").HasValue("A"))
.Map<MyBaseClassB>(m => m.Requires("Abbrev").HasValue("B"));
}
The problem is when I want to use such mapping - I can't use the discriminator field (Table1.Abbrev) as a part of a composite key in the MyBaseClass - I get the following error:
All objects in the EntitySet 'DataContext.MyBaseClass' must have unique primary keys. However, an instance of type 'MyBaseClassA' and an instance of type 'MyBaseClassB' both have the same primary key value, 'EntitySet=MyBaseClass;Code=1'.
Is it possible to map the model above with Entity framework 6 (or newer)?