我正在尝试更新 EF6 中的实体。我读过如果我想更改 ForeignKey 属性,则必须确保 Navigation 属性是正确的,或者将其设置为 null。
我已经采用设置为空的方法,但我仍然收到引用完整性约束异常:
A referential integrity constraint violation occurred: The property value(s) of 'Contact.idContact' on one end of a relationship do not match the property value(s) of 'Entity.id_EntityContactInfo' on the other end.
但是您可以在调试器中看到,Entity.Contact 为空,所以我认为这不应该抛出。
有什么想法吗?
编辑
实体是这样更新的:
public T CommitUpdate<T>(T obj) where T : class
{
_DbContext.Set<T>().Attach(obj);
_DbContext.Entry(obj).State = EntityState.Modified;
_DbContext.Commit();
return obj;
}
最佳答案
我从评论中看到,您正在解决这个问题:
I want to change the FK scalar, but not add the current item into the database again
你应该有这样的映射:
public class MyEntity {
...
public int ContactId { get; set; }
[ForeignKey("ContactId")]
public Contact Contact { get; set; }
...
}
由于 FK 被声明为不可为空,因此您必须对其进行设置。
基本上你有几种选择:
设置
ContactId
为数据库中的真实ID,设置Contact
为null在这种情况下,您将使用数据库中的现有联系人更新 FK - 希望是您需要的选项。
将
ContactId
设置为0,将Contact
设置为new Contact(..)
在这种情况下,EF 将首先尝试在 DB 中创建新的
Contact
,然后使用它的 PK 来提供ContactId
FK。创建空的
Contact
实体,将其 ID 设置为现有的联系人 ID。然后,将此实体用作相关实体的联系人字段。然后,将该Contact
附加到具有 UnChanged 状态的上下文。有了这个,你会告诉 EF 这个联系人已经存在,不应该被跟踪并且不应该被改变,但是它的 ID 将被用作你父实体的 FK。请注意,此联系人应附加(处于未更改状态)与其父级相同的上下文。
关于c# - 尝试将 FK 设置为 null 时违反参照完整性约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25320296/