尝试将FK设置为​​null时违反引用完整性约束 [英] Referential Integrity Constraint violation when attempting to set a FK to null

查看:334
本文介绍了尝试将FK设置为​​null时违反引用完整性约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新EF6中的实体。我已经读过,如果要更改ForeignKey属性,则必须确保Navigation属性是正确的属性,或将其设置为null。

I am trying to update an entity in EF6. I have read that if I wish to change a ForeignKey property, I have to then ensure the Navigation Property is the correct one, or set it to null.

设置为null的方法,但我仍然收到引用完整性约束异常:

I have taken the set to null approach, but I still receive the Referential Integrity Constraint Exception:

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为空,所以我认为这不应该

But you can see in the debugger, that Entity.Contact is null, so I believe this shouldn't be throwing.

有任何想法吗?

编辑

这是如何更新实体:

public T CommitUpdate<T>(T obj) where T : class
    {
        _DbContext.Set<T>().Attach(obj);
        _DbContext.Entry(obj).State = EntityState.Modified;
        _DbContext.Commit();
        return obj;
    }


推荐答案

从我在评论中看到的,您正在解决此问题:

From what I see from comments, you are solving this problem:



我想更改FK标量,但不添加当前项目再次进入数据库

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被声明为不可为空,则必须对其进行设置。

As FK is declared as not-nullable, you have to set it.

基本上,您可以通过以下几种方法进行选择:

Basically you have several options to do it:


  • ContactId 设置为数据库中的真实ID,将 Contact 设置为空

  • Set ContactId to real ID in database, set Contact to null

在这种情况下,您将使用数据库中现有的Contact更新FK-希望有您需要的选项。

In this case, you will update FK with existing Contact in DB - hopefully the option you need.

设置 ContactId 设置为0,并将 Contact 设置为 new Contact(..)

Set ContactId to 0, and set Contact to new Contact(..)

在这种情况下,EF会先尝试在数据库中创建新的 Contact ,然后再使用其PK来填充 ContactId FK。

In this case, EF will try to create new Contact in DB first, and then will use its PK to feed ContactId FK.

创建空的联系人实体,将其ID设置为现有的联系人ID。然后,将此实体用作所涉及实体的联系人字段。然后,将该联系人附加到具有未更改状态的上下文。

Create empty Contact entity, set its ID to existing contact ID. Then, use this entity as Contact field for your entity in question. Then, attach that Contact to context with UnChanged state.

有了这个,您将对EF说此联系人已经存在,不应对其进行跟踪和更改,但其ID将用作您的FK父实体。请注意,此联系人应与其父对象附加(处于不变状态)。

Having this, you will say to EF that this Contact is already existing, should not be tracked and should not be changed, but its ID will be used as FK for your parent entity. Just take care that this Contact should be attached (in unchanged state) to the same context as its parent.

这篇关于尝试将FK设置为​​null时违反引用完整性约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆