I am having an issue with how the database is being generated for an inheritance relationship in my entity classes. It is correctly making the primary key ID in the subclass table reference the ID in the superclass table – but it is also creating a foreign key in the superclass table which it doesn’t need. Here are my classes:
Abstract superclass:
public abstract class DaqObject
{
public int ID { get; set; }
public int AgencyID { get; set; }
public int DaqObjectTypeID { get; set; }
[ForeignKey("AgencyID")]
public virtual Agency Agency { get; set; }
[ForeignKey("DaqObjectTypeID")]
public virtual DaqObjectType DaqObjectType { get; set; }
public virtual Document InheritingDocument { get; set; }
}
The corresponding database table has the following columns:
- ID (PK, int, not null)
- AgencyID (FK, int, not null)
- DaqObjectTypeID (FK, int, not null)
- InheritingWell_ID (FK, int, null)
Subclass:
public class Document : DaqObject
{
public string Name { get; set; }
}
With a corresponding database table with the following columns:
- ID (PK, FK, int, not null)
- Name (nvarchar(max), null)
(These classes have been slimmed down for the example.)
The DaqObject table in the database ends up with an InheritingDocument_ID column. I can create the database myself and make the relationship without that foreign key in the superclass table. Is it possible to have EF code first do the same?
The
InheritingDocumentin theDaqObjecttells EF to create one:many relationship betweenDocumentandDaqObjectentities. That’s why there is theInheritingDocument_IDcolumn in your DB.I suppose, it isn’t what you want, you have added the
InheritingDocumentproperty to make inheritance work, right? It isn’t necessary, EF will take care of inheritance handling automatically. There is a nice blog post, that describes possible strategies for working with inherited classes with the EF.