A referential integrity constraint violation occurred

前端 未结 6 1177
有刺的猬
有刺的猬 2021-01-18 04:54

I\'m trying to update an existing entity.

I have the following code:

public MamConfiguration_V1 Save(MamConfiguration_V1 item)
{
    mMaMDBEntities.M         


        
相关标签:
6条回答
  • 2021-01-18 05:36

    This might be an old post but the following worked for me

    set the SaveOptions option to SaveOptions.DetectChangesBeforeSave

    0 讨论(0)
  • 2021-01-18 05:37

    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. EF will automatically populate the CurrentLocation object because CurrentLocationId has a foreign key in the CurrentLocation's table. When you edit the CurrentLocationId without updating the CurrentLocation object as well, they become out of sync. This is what causes the exception in this case.

    So let's say you needed to update the Person object's CurrentLocationId. We'll assume you pre-fetched the Person data and the Location data.

    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();
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-18 05:40

    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. 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). The specific circumstances did not allow O.Item to be loaded.

    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.

    0 讨论(0)
  • 2021-01-18 05:57

    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.

    0 讨论(0)
  • 2021-01-18 05:58

    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. To resolve it, I used context.Entry(Object).State = EntityState.Detached, reloaded the object, made the foreign key change and then saved my changes

    0 讨论(0)
  • 2021-01-18 05:59

    Seems like you have some relationship with foreign key field and a navigation property in the item, and those fields have conflicting values. 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. Make sure you modify relationship at both ends and mark all the affected entities as Modified before calling SaveChanges.

    0 讨论(0)
提交回复
热议问题