So I have the following code:
ParentModel.cs
public class ParentModel {
public int ParentModelID {get; set;}
...other fields here
public ChildModel ChildModel {get; set;}
}
ChildModel.cs
public class ChildModel{
[ForeignKey("ParentModel")]
public int ChildModelID {get; set;}
...other fields and navigation properties here
public int ParentModelID {get; set;}
public ParentModel ParentModel {get; set;}
}
So the database gets generated successfully. The problem occurs when I try to save data. For example I save data to the ParentModel
first and it gets save successfully. But when I save inside ChildModel
, even when my data contains the ParentModel
's id, it gives me the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.ChildModels_dbo.ParentModels_ChildModelID". The conflict occurred in database "MyDatabaseName", table "dbo.ParentModels", column 'ParentModelID'. The statement has been terminated.