EF wrote a simple framework. When modifying the queried data back, it reported that the objectstatemanager already has an object with the same key, searching finally found the final solution.
An object with the same key already exists in objectstatemanager. Objectstatemanager cannot trace multiple objects with the same key.
Note: unprocessed exceptions occur during the execution of the current Web request. Check the stack trace information for details about the error and the source of the error in the code.
Exception details: system. invalidoperationexception: an object with the same key already exists in objectstatemanager. Objectstatemanager cannot trace the same
Key.
Some information on the internet says that the database. Entry (Entity). State = entitystate. detached state is changed first and then modified. However, I wrote the method in the base class, passed the generic T, and I did not inherit all models from the basemodel, so t cannot get the primary key, therefore, you cannot find this object in the database. If you change the state of the object, an error is returned.
Therefore, this method does not work. We can only find another method. After finding the information, we found that this is because of the data after the query. EF caches the data for us by default and stores it in the dbcontext context. When we modify the data, the database must be operated. entry (entity ). state = entitystate. modified; when you need to append the object to the next object, EF finds that the object has been appended, so this error is reported. So naturally there is a solution.
Solution: Add asnotracking () to the query... In this way, EF will not cache the queried objects!
The update method is written as follows:
Public Virtual bool Update (T entity) {dB. Entry (Entity). State = entitystate. Modified; return true ;}
Entity framework5.0 runtime error objectstatemanager an object with the same key already exists