I have following 2 classes.
public partial class Query
{
public int Id { get; set; }
public virtual QueryGroup QueryGroup { get; set; }
}
public partial class QueryGroup
{
public int Id { get; set; }
public virtual ICollection<Query> Query { get; set; }
}
Now these 2 classes are parsed from json. so both Ids are 0, because it is adding (not updating).
When I do below.
projectContext.SaveChanges();
It gives below error, how to add them both in single statement. or will it require seperate add?
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Query_QueryGroup". The conflict occurred in database "Project", table "dbo.QueryGroup", column 'Id'.
If you are trying to insert data into Query you must have data with ForeignKey in table QueryGroup so you could add data to both tables and then SaveChanges
As per the conflict mentioned by you, below is my opinion:
If you have a table A having a foreign-key to table B, then while adding a record to table A the foreign-key value must exist in the table B. If the foreign-key value does not exist in table B then the above mentioned SqlException occurs.
Hence you need to add data to table B first and then table A. You can create a single sql transaction for this.