A referential integrity constraint violation occurred

前端 未结 6 1179
有刺的猬
有刺的猬 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: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 PersonList;
        List 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();
            }
        }
    }
    

提交回复
热议问题