I'm using code-first to create my databases in Entity Framework, and am using the Table per Hierarchy approach for the inheritance hierarchy for the class shown below.
When I run a migration everything works, but when I update my database I get the following error:
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.BaseStatus_dbo.Rider_ID". The conflict occurred in database "ASPNET_INSURANCE_c48b7267b7cd4bac952caa1a467ab9ae", table "dbo.Rider", column 'ID'.
I have a class that has a navigation property to a derived class. (Simplified code)
public class Rider
{
public int ID { get; set; }
public virtual DerivedStatus derivedStatus { get; set; }
}
The derived classes with data annotations look like so:
public class BaseStatus
{
[Key, ForeignKey("rider")]
public int ID { get; set; }
public bool? Married { get; set; }
public virtual Rider rider { get; set; }
}
public class DerivedStatus : BaseStatus
{
public bool? HomeOwnership { get; set; }
}
For the DbContext I have just added the following to create the table which works as expected (all properties in one table with a Discriminator column).
public DbSet<BaseStatus> Status { get; set; }
The relationship between the Rider and the derived class is one-to-one.
I'm not sure if it's relevant/of help, but below is part of the DbMigration file which is generated:
CreateTable(
"dbo.Rider",
c => new
{
ID = c.Int(nullable: false, identity: true),
CorrelationID = c.Guid(),
derivedStatus_ID = c.Int(),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.BaseStatus", t => t.derivedStatus_ID)
.Index(t => t.derivedStatus_ID);
When updating the database I'm also seeding it with some test data which I guess is when it picks up on this problem.
This is the first time I'm using inheritance in Entity and I'm not sure where the problem lies. I've tried dropping my database and re-running migrations as I'd read this can sometimes cause problems but I got the same error message.
Going forward there will likely be further derived classes of both the BaseStatus and Rider classes, with different derived Riders using different Status classes so any solution must be scalable. It may be that when the project grows I'll change from Table per Hierarchy to Table per Type, but for now I'd like a solution for TPH (if it's possible)