简体   繁体   English

发生了参照完整性约束违规

[英]A referential integrity constraint violation occurred

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: Attach方法抛出异常:

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? 我怎样才能解决这个问题?

Seems like you have some relationship with foreign key field and a navigation property in the item , and those fields have conflicting values. 好像你有外键字段,并在一些关系的导航属性item ,而这些领域有冲突的值。 This occurs when you load an entity and its related entities, change the relationship at one end, mark only that end as Modified and attempt to save. 当您加载实体及其相关实体,在一端更改关系,仅将该末端标记为已Modified并尝试保存时,会发生这种情况。 Make sure you modify relationship at both ends and mark all the affected entities as Modified before calling SaveChanges . 确保在调用SaveChanges之前修改两端的关系并将所有受影响的实体标记为已Modified

What is the definition of the item object? item对象的定义是什么? 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. 您可以添加System.Data的使用,以避免一直写入它。

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. 这是一行而不是两行。

I encountered this exception under a different set of circumstances, and am posting here since this question comes up when the error message is searched. 我在不同情况下遇到此异常,并且在此处发布,因为在搜索错误消息时会出现此问题。

The exception was thrown when calling IObjectContextAdapter.ObjectContext.AttachTo(entitySetName, entity) with a partially-loaded entity. 使用部分加载的实体调用IObjectContextAdapter.ObjectContext.AttachTo(entitySetName, entity)时抛出异常。 The foreign keys on the entity were defined, but the navigational properties were not loaded. 定义了实体上的外键,但未加载导航属性。 (That is, O.ItemID had a value, but O.Item was null). (也就是说, O.ItemID有一个值,但O.Item为null)。 The specific circumstances did not allow O.Item to be loaded. 具体情况不允许加载O.Item

The problem turned out to be that the Object State Manager had loaded the object in a separate method and was already tracking the object defined with the same keys. 问题是,对象状态管理器已经在一个单独的方法中加载了对象,并且已经跟踪了使用相同键定义的对象。 Since the separate method did not need to track the object state, the issue was resolved by calling IQueryable.AsNoTracking() within that method. 由于单独的方法不需要跟踪对象状态,因此通过在该方法中调用IQueryable.AsNoTracking()解决该问题。

The issue for me was that entity framework had loaded my object in multiple places, so when I updated a foreign key, there were now two references to the same object, one with a foreign key pointing to record a and one with a foreign key pointing to record b, which caused an error since my relationship is one to one. 对我来说问题是实体框架已经在多个地方加载了我的对象,所以当我更新外键时,现在有两个对同一个对象的引用,一个用外键指向记录a,一个用外键指向记录b,因为我的关系是一对一的,所以导致错误。 To resolve it, I used context.Entry(Object).State = EntityState.Detached, reloaded the object, made the foreign key change and then saved my changes 为了解决它,我使用了context.Entry(Object).State = EntityState.Detached,重新加载了对象,使外键发生了变化,然后保存了我的更改

Lets say you have the following schema: 假设您有以下架构: 模式

If you want to edit the CurrentLocationId in Person, you also need to edit the CurrentLocation object embedded in the Person object. 如果要编辑Person中的CurrentLocationId,还需要编辑Person对象中嵌入的CurrentLocation对象。 EF will automatically populate the CurrentLocation object because CurrentLocationId has a foreign key in the CurrentLocation's table. EF将自动填充CurrentLocation对象,因为CurrentLocationId在CurrentLocation的表中有一个外键。 When you edit the CurrentLocationId without updating the CurrentLocation object as well, they become out of sync. 当您编辑CurrentLocationId而不更新CurrentLocation对象时,它们会变得不同步。 This is what causes the exception in this case. 这是导致这种情况下的异常的原因。

So let's say you needed to update the Person object's CurrentLocationId. 所以假设你需要更新Person对象的CurrentLocationId。 We'll assume you pre-fetched the Person data and the Location data. 我们假设您预先获取了Person数据和Location数据。

public class DbData 
{
    List<Person> PersonList;
    List<Location> LocationList;
    public DbData()
    {
        using (var context = new MyContext())
        {
             PersonList = context.Persons.ToList();
             LocationList = context.Locations.ToList();
        }
    }

    public void UpdatePersonLocation(Person person, int newLocationId)
    {
        using (var context = new MyContext())
        {
            var location = LocationList.Where(l=>l.id==newLocationId).Single();
            //you need to update both the id and the location for this to not throw the exception
            person.CurrentLocationId == newLocationId;
            person.CurrentLocation == location;  
            context.Entry(person).State = System.Data.Entity.EntityState.Modified;
            context.SaveChanges();
        }
    }
    //or if you're giving it the location object...
    public void UpdatePersonLocation(Person person, Location location)
    {
        using (var context = new MyContext())
        {
            //you need to update both the id and the location for this to not throw the exception
            person.CurrentLocationId == location.id;
            person.CurrentLocation == location;  
            context.Entry(person).State = System.Data.Entity.EntityState.Modified;
            context.SaveChanges();
        }
    }
}

This might be an old post but the following worked for me 这可能是一个旧帖子,但以下对我有用

set the SaveOptions option to SaveOptions.DetectChangesBeforeSave SaveOptions option设置为SaveOptions.DetectChangesBeforeSave

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 发生参照完整性约束违规 - Referential integrity constraint violation occurred 错误“发生了参照完整性约束冲突” - Error “A referential integrity constraint violation occurred” 发生参照完整性约束冲突 Nullable FK - A referential integrity constraint violation occurred Nullable FK 发生参照完整性约束冲突。 更新EF时 - A referential integrity constraint violation occurred. When Updating EF 向EF添加新实体时出错:发生了参照完整性约束违规 - Error when adding new entity to EF : A referential integrity constraint violation occurred 尝试在Entity Framework中进行更新时出现错误“发生了引用完整性约束冲突” - Error “A referential integrity constraint violation occurred” when trying update in Entity Framework 实体框架迁移-违反参照完整性约束 - Entity Framework Migrations - A referential integrity constraint violation EF 6 Code First,使用包含在导航属性上的外键ID更改会导致“发生引用完整性约束违规”错误 - EF 6 Code First, changing a Foreign Key Id with an Include on navigation property causes “A referential integrity constraint violation occurred” error 保存包含列表的对象会产生“违反参照完整性约束” - Saving an Object that contains a list gives “referential integrity constraint violation” 尝试将FK设置为​​null时,引用完整性约束违规 - Referential Integrity Constraint violation when attempting to set a FK to null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM