c# - 尝试将 FK 设置为 null 时违反参照完整性约束

标签 c# entity-framework referential-integrity

我正在尝试更新 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 为空,所以我认为这不应该抛出。

enter image description here

有什么想法吗?

编辑

实体是这样更新的:

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/

相关文章:

c# - 在分离场景中使用独立关联时更新一对多实体

entity-framework - 具有现有域模型的 Entity Framework 4

mysql - 检查引用完整性中断

mysql禁用参照完整性

entity-framework - 我可以一次性忽略 Automapper 属性吗?

c# - 如何处理来自不同时区的时间戳数据?

c# 无法解析 xml,收到错误 463

c# - 正则表达式允许所有字符,长度应为 1-50 个字符

database - 外键有什么问题?

c# - 接口(interface)设计实现错误: . ..无法实现...因为它没有匹配的返回类型