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

后端 未结 2 1505
青春惊慌失措
青春惊慌失措 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 12:44

    Try just getting the entity by id rather than creating a new with fixed id:

    var UpdateLocation = db.Locations.FirstOrDefault( l => l.ID == model.ID );
    
    UpdateLocation.Description = model.Description;
    ...
    

    The reason you see your exception is because your

    model.ParentLocations = ...
    

    materializes entities that most probably include the one you try to modify. Thus, the entity is already in the first level cache.

    But then you try to pretend yet another entity of the same id exists.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题