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

后端 未结 2 1532
青春惊慌失措
青春惊慌失措 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.

提交回复
热议问题