Skip to content
Advertisement

The INSERT statement conflicted with the FOREIGN KEY constraint in Entity framework core, 2 tables in single statement

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’.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement