I am facing a problem with EF Code First with TPH. I am getting two additional columns in the table which is not in the model.
I have a class structure as following :
public class TestBase
{
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("TestMaster")]
public string TestMaster_Id { get; set; }
public TestMaster TestMaster { get; set; }
}
public class TestInherit1 : TestBase
{
public string Val1 { get; set; }
}
public class TestInherit2 : TestBase
{
public string val2 { get; set; }
}
public class TestMaster
{
[Key]
public string Id { get; set; }
public virtual ICollection<TestInherit1> Inherit1List { get; set; }
public virtual ICollection<TestInherit2> Inherit2List { get; set; }
}
In DBContext I have the following :
public DbSet<TestMaster> TestMaster
{
get;
set;
}
public DbSet<TestBase> TestBase
{
get;
set;
}
[NotMapped]
public DbSet<TestInherit1> TestInherit1
{
get;
set;
}
[NotMapped]
public DbSet<TestInherit2> TestInherit2
{
get;
set;
}
The following is the EF generated tables structure:
[TestBases]
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[TestMaster_Id] [nvarchar](128) NULL,
[Val1] [nvarchar](max) NULL,
[val2] [nvarchar](max) NULL,
[Discriminator] [nvarchar](128) NOT NULL,
[TestMaster_Id1] [nvarchar](128) NULL,
[TestMaster_Id2] [nvarchar](128) NULL
[TestMasters](
[Id] [nvarchar](128) NOT NULL
If you look at the TestBases table, there are two additional columns TestMaster_id1 and TestMaster_Id2 being generated , that is not defined in the class. EF is inserting those two columns . I already have the foreign key defined on the column TestMaster_Id. What am I doing wrong?. I do not want these two columns.
Your table contains more undefined columns:
Val1,Val2andDiscriminatorshould also not be mapped if you don’t want to map derived types. But if you don’t map those types you will never get those instances from EF and you will never be able to store that instances to EF.Your
NotMappedattribute is used incorrectly. It must be declared either on entity type or on property inside entity type. Also if you don’t want to map derived types you should not createDbSetproperties for them.The correct usage of the attribute is either:
Or:
At the moment your entities are mapped and that is also a reason why you get two new foreign keys – you defined navigation properties to derived types. Each of them needs its own foreign key because EF is not able to redefine mapping of parent properties in derived class.
If you want only single foreign key declared in the parent entity you must define only single navigation property to the parent: