简体   繁体   English

当未修改外键值时,UPDATE语句与FOREIGN KEY约束冲突

[英]The UPDATE statement conflicted with the FOREIGN KEY constraint when foreign key value is untouched

I am using SQL through C# to make an update to a row in a table as shown below 我正在通过C#使用SQL来更新表中的一行,如下所示

context.AssessmentInvitation.Attach(assessmentInvitation);
context.Entry(assessmentInvitation).State = EntityState.Modified;
await context.SaveChangesAsync();

When this is executed in some cases, I get an exception on SaveChangesAsync due to a foreign key constraint. 在某些情况下执行此操作时,由于外键约束,我在SaveChangesAsync上遇到异常。 The foreign key constraint has to do with a CompanyId as part of the assessmentInvitation object being updated. 外键约束与CompanyId ,这是要更新的assessmentInvitation对象的一部分。 This constraint is set to cascade on update, which seems to be the common solution to this issue. 此约束设置为在更新时级联,这似乎是此问题的常见解决方案。 This did not resolve the issue for me. 这并没有为我解决问题。

The interesting thing is that the update causing this issue is not touching this foreign key at all. 有趣的是,导致此问题的更新根本没有触及此外键。 It is only updating a BIT to set it to true. 它只是更新BIT以将其设置为true。 No other values are being modified. 没有其他值被修改。 The BIT is not related to any other table in any way, it is not part of any type of key. BIT绝不与任何其他表相关,它也不是任何类型的键的一部分。

Why would this foreign key constraint be relevant to the update at all if it is remaining the same? 如果外键约束保持不变,为什么它与更新完全相关? How can I fix this issue? 如何解决此问题?

edit: The problem was much more simple than I thought. 编辑:问题比我想象的简单得多。 It was using a stored procedure that was not fetching the entire AssessmentInvitation object. 它使用的存储过程未获取整个AssessmentInvitation对象。 Actually, it excluded the CompanyId completely. 实际上,它完全排除了CompanyId。 So when I tried to update without the existing CompanyId, obviously it failed. 因此,当我尝试在没有现有CompanyId的情况下进行更新时,显然失败了。 I thought I was going to learn something about Entity Framework, instead I realized I'm not very good at going through other people's code. 我以为我要学习有关实体框架的知识,相反,我意识到自己不太擅长阅读别人的代码。

I can't add a comment so I'm posting an answer hope it helps you, 我无法添加评论,所以我发布了一个答案,希望对您有帮助,

try to inspect the properties of assessmentInvitation to see if it holds a correct companyId value, if you are creating the object or created by the model binder in request it may has it's CompanyId set to null. 尝试检查assessmentInvitation的属性以查看其是否具有正确的companyId值,如果您正在创建对象或由请求中的模型绑定程序创建的对象,则其CompanyId可能设置为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM