[英]The INSERT statement conflicted with the FOREIGN KEY constraint in Entity framework core, 2 tables in single statement
I have following 2 classes.我有以下2节课。
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.现在这两个类是从 json 解析出来的。 so both Ids are 0, because it is adding (not updating).
所以两个 Id 都是 0,因为它正在添加(不更新)。
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".
SqlException: INSERT 语句与 FOREIGN KEY 约束“FK_Query_QueryGroup”冲突。 The conflict occurred in database "Project", table "dbo.QueryGroup", column 'Id'.
冲突发生在数据库“Project”、表“dbo.QueryGroup”、“Id”列中。
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 .如果表A具有表B的外键,则在向表A 中添加记录时,表B 中必须存在外键值。 If the foreign-key value does not exist in table B then the above mentioned SqlException occurs.
如果表B中不存在外键值,则发生上述 SqlException。
Hence you need to add data to table B first and then table A .因此,您需要先将数据添加到表B 中,然后再将数据添加到表A 中。 You can create a single sql transaction for this.
您可以为此创建单个 sql 事务。
如果您尝试将数据插入Query ,则表QueryGroup 中必须有带有 ForeignKey 的数据,以便您可以将数据添加到两个表,然后SaveChanges
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.