Error attaching entity because of same primary key when trying to save an update

后端 未结 2 1504
青春惊慌失措
青春惊慌失措 2021-01-12 12:22

I am trying to save an update to an existing database entry but when I do I get the error:

Attaching an entity of type \'FFInfo.DAL.Location\' failed

2条回答
  •  清酒与你
    2021-01-12 13:01

    You can not have two entities (same type) with same primary keys in memory in Entity Framework.

    The problem is

    model.ParentLocations = new SelectList(db.Locations.Where(l => l.SectionID == model.Section).OrderBy(l => l.Name), "ID", "Name").ToList();
    

    in above line you somehow have loaded the Location which its ID is model.ID

    then in

    var UpdatedLocation = new Location()
    {
        Description = model.Description,
        GeographyTypeID = model.GeographyType,
        ID = model.ID,
        MapFileID = model.MapFileID,
        Name = model.Name,
        ParentLocationID = model.ParentLocation,
        SectionID = model.Section
    };
    db.Entry(UpdatedLocation).State = EntityState.Modified;
    

    You are creating a new Location and trying to attach it to context (by setting it's state as modified), but you have loaded another Location entity with exact primary key as UpdatedLocation into memory somewhere and this cause the exception.

    Try fetching the the location and then change the roperties.

    var UpdateLocation = db.Locations.First(l => l.ID == model.ID);
    // var UpdateLocation = db.Locations.Find(model.ID); maybe a better option
    UpdatedLocation.Description = model.Description;
    UpdatedLocation.GeographyTypeID = model.GeographyType;
    UpdatedLocation.MapFileID = model.MapFileID;
    UpdatedLocation.Name = model.Name;
    UpdatedLocation.ParentLocationID = model.ParentLocation;
    UpdatedLocation.SectionID = model.Section;
    

提交回复
热议问题