Entity Framework The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
Check that there is not existing data in the database that is conflicting with the FK constraint causing the creation to fail.
I think @Cory was getting you close to the correct solution, you just did not take the time to investigate.
In add-migration code, the migration probably generated
public override void Up()
{
AddColumn("dbo.ClientContacts", "FamilialRelationshipId", c => c.Int(nullable: false));
CreateIndex("dbo.ClientContacts", "FamilialRelationshipId");
AddForeignKey("dbo.ClientContacts", "FamilialRelationshipId", "dbo.FamilialRelationships", "FamilialRelationshipId");
}
Notice nullable:false; If your Model had an Id of int instead of int? (nullable int) the migration code will set nullable to false. Your model shows you are using a non-nullable int which defaults to 0, and you probably don't have a foreign key item with a value of 0.
Now, you will have to either create a default value, that exists in the foreign key table, or Create the Constraint with no check if you are using SQL Server to create the constraint. Remember this though: If you decorate your property with a [DefaultValue(0)] attribute, it won't change the existing data, like a SQL Column Add would, if a default value was specified.
I recommend you change your Model Class to allow a nullable int. Then, in your seed method, create a simple method against dbcontext to update the new column with a default value, because the [DefaultValue] attribute in data annotations will not modify your data.
Add-Migration / Update-Database to create the column and constraint. Next, modify your model if you desire to allow for a non-nullable int, and presuming you changed all rows to some valid value for the foreign key, Add-Migration / Update-database again. This gives you an unbroken chain in your model migration. Will come in handy later when you publish to a live site, because the flow of your data model changes will be intact.
- Hope this helps.
This error is telling you that you are violating the foreign key constraint. To resolve you have a few solutions
- Fix your data - Somewhere there are records in the
Clients
table that have a MedicalGroupId that does not exist in the in theMedicalGroups
table. Write a query to find out what IDs do not exist in theMedicalGroups
table and manually fix the data yourself. - Remove the foreign key constraint - Obviously if you remove the foreign key constraint you will no longer be bothered by this message. Unfortunately the database will no longer enforce this relationship and might make this problem worse in the future.
- Create constraint using
WITH NOCHECK
- You can create your foreign key constraint using theWITH NOCHECK
option. This option tells SQL Server to not apply this constraint to existing data. SQL Server WILL check this constraint in any future INSERTS/UPDATES/DELETES.