[英]C# Entity Framework, deleting child items then parent, The DELETE statement conflicted with the REFERENCE constraint
Trying to delete child items first, then the parent.尝试先删除子项,然后是父项。 I am inside the same using statement.
我在同一个 using 语句中。
Originally I had one call to context.SaveChanges();
最初我有一次调用
context.SaveChanges();
but I have changed to commit the child delete first, then try and delete the parent records, but I am still sometimes receiving this error message:但我已更改为先提交子删除,然后尝试删除父记录,但有时我仍会收到此错误消息:
The DELETE statement conflicted with the REFERENCE constraint “FK_AccountQuestionMappings_AccountQuestions”.
DELETE 语句与 REFERENCE 约束“FK_AccountQuestionMappings_AccountQuestions”冲突。 The conflict occurred in database “db”, table “dbo.AccountQuestionMappings”, column 'QuestionId'.
冲突发生在数据库“db”、表“dbo.AccountQuestionMappings”、列“QuestionId”中。 The statement has been terminated.
该语句已终止。
So the relationship is the questions in table AccountQuestions
are the parent, and these are mapped and stored in the AccountQuestionMappings
table.所以关系是表
AccountQuestions
中的问题是父问题,这些问题被映射并存储在AccountQuestionMappings
表中。 I am trying to delete them from the AccountQuestionMappings
table, then from the AccountQuestions
table.我试图从
AccountQuestionMappings
表中删除它们,然后从AccountQuestions
表中删除它们。
using (var db = dataContext())
{
if(questionInfo != null)
{
var questionIds = db.AccountQuestions.Where(q => q.AccountQuestionInfoId == questionInfo.Id).Select(s => s.Id).ToList();
foreach (var question in questionIds)
{
var questionMapping = db.AccountQuestionMappings.Where(q => q.QuestionId == question).FirstOrDefault();
if (questionMapping != null)
{
db.AccountQuestionMappings.Remove(questionMapping);
}
}
db.SaveChanges();
db.AccountQuestions.RemoveRange(db.AccountQuestions.Where(s => s.AccountQuestionInfoId == questionInfo.Id));
db.SaveChanges(); // error occurs on this line saying due to there still being a child in the mappings table
}
}
You are using FirstOrDefault()
to delete AccountQuestionMappings
.您正在使用
FirstOrDefault()
删除AccountQuestionMappings
。 So if there are multiple AccountQuestionMappings
associated with AccountQuestions
then it will only delete first
one.因此,如果有多个
AccountQuestionMappings
与AccountQuestions
关联,那么它只会删除first
一个。 So when you delete AccountQuestions
it will throw error.因此,当您删除
AccountQuestions
时,它会引发错误。
You can try updating code like below.您可以尝试更新如下代码。 Remove
FirstOrDefault()
.删除
FirstOrDefault()
。 Update condition inside if
statement.更新
if
语句中的条件。 And use RemoveRange
.并使用
RemoveRange
。
foreach (var question in questionIds)
{
var questionMapping = db.AccountQuestionMappings.Where(q => q.QuestionId == question);
if (questionMapping.Count() > 0)
{
db.AccountQuestionMappings.RemoveRange(questionMapping);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.