Referential Integrity Constraint violation when attempting to set a FK to null

ぃ、小莉子 提交于 2019-11-30 19:25:08

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

I want to change the FK scalar, but not add the current item into the database again

You should have mapping something like this one:

public class MyEntity {
    ...

    public int ContactId { get; set; }

    [ForeignKey("ContactId")]
    public Contact Contact { get; set; }
    ...
}

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

Basically you have several options to do it:

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

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

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

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

  • 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.

    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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!