引发完整性约束违规发生 [英] A referential integrity constraint violation occurred

查看:141
本文介绍了引发完整性约束违规发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下代码:

  public MamConfiguration_V1 Save(MamConfiguration_V1 item)
{
mMaMDBEntities.MamConfiguration_V1.Attach(item);
mMaMDBEntities.ObjectStateManager.ChangeObjectState(item,System.Data.EntityState.Modified);
mMaMDBEntities.SaveChanges();
返回项目;
}

但是 Attach 方法抛出异常:


发生参照完整性约束违规:定义参照约束的属性值在主体和从属对象之间不一致


我如何解决这个问题?

解决方案

项目对象的定义是什么?看来,在与其他实体设立争执的一些集合中,存在一些类型的冲突。您可以尝试清除所有集合以查看问题是否仍然存在,但在这种情况下,您丢失了外键分配。但也许这可以帮助您找到问题。



这可能是一个提示。当我尝试将现有实体附加到上下文中时,我使用以下操作:

  mMaMDBEntities.Entry& MamConfiguration> item).State = System.Data.EntityState.Modified; 

您可以添加使用System.Data,以避免一直写入它。 / p>

将实体附加到您想要的状态,在此情况下进行修改并跟踪更改。这是一行而不是两行。


I'm trying to update an existing entity.

I have the following code:

public MamConfiguration_V1 Save(MamConfiguration_V1 item)
{
    mMaMDBEntities.MamConfiguration_V1.Attach(item);
    mMaMDBEntities.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Modified);
    mMaMDBEntities.SaveChanges();
    return item;
}

But the Attach methods throws an exception:

A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.

How can I fix this?

解决方案

What is the definition of the item object? It seems that in some of its collections that set the realionship with other entities exist some type of conflict. You could try to clear all the collections to see if the problem persists, but in this case you lost the foreign key assignment. But perhaps it could help you to locate the problem.

This could be a tip. When I try to attach an existing entity to the context, I use to do the following:

mMaMDBEntities.Entry<MamConfiguration>(item).State = System.Data.EntityState.Modified;

You can add the using of System.Data to avoid the needed to write it all the time.

This attach the entity in the state that you want, modified in this case and track the changes. This is one line instead of two.

这篇关于引发完整性约束违规发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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