When using EF to update data, the following error is reported:
An object with the same key already exists in the Objectstatemanager. Objectstatemanager cannot track multiple objects with the same key.
The reason is that 2 entities with the same key are not allowed in the context of EF. The following (the underlined code is OK):
public static Object Bacthsave<t> (String insertedrows, String updatedrows, String deletedrows) where t:class{T ry {//Add if (!string. IsNullOrEmpty (insertedrows)) {list<t> insertedlist = jsonhelper.deserializedata<list<t>& gt; (insertedrows); foreach (var model in insertedlist) {//db. Sys_navigations.add (BTN); Db. Entry (model). state = entitystate.added; }//db. Sys_buttons.add (unicorn);//Add to context//INSERT INTO Database}//Modify if (!string. IsNullOrEmpty (updatedrows)) {Type type = typeof (T);list<t> updatedlist = jsonhelper.deserializedata<list<t>> (updatedrows);PropertyInfo PropertyInfo = type. GetProperty ("Id");foreach (var model in updatedlist) {//Note the following hint content, property name, type of property
string n = propertyinfo.name; n = propertyInfo.PropertyType.Name; n = propertyInfo.PropertyType.FullName;nullable<int> id = propertyinfo.getvalue (model) as nullable<int>;String id = model. GetType (). InvokeMember ("Id", System.Reflection.BindingFlags.GetProperty, NULL, model, NULL) as string;//This method did not test pass, do not know why, beg messagevar entry = db. Entry (model); if (entry. state = = entitystate.detached) { var set = db. Set<t> (); T attachedproduct = set. Local.singleordefault (p = propertyinfo.getvalue (p) as int = = = id);If the context is already being tracedif (attachedproduct! = null) { var attachedentry = db. Entry (attachedproduct); attachedEntry.CurrentValues.SetValues (model); } else//If not tracked in the current context { entry. state = entitystate.modified; } }Db. Entry (model). state = entitystate.modified; }}//delete if (!string. IsNullOrEmpty (deletedrows)) {list<t> deletedlist = Jsonhelper.deserializedata<list<t>> ;(d eletedrows); foreach (var model in deletedlist) {db. Entry (model). state = entitystate.deleted; Db. Sys_buttons.remove (BTN);//You can also use this method}}db. SaveChanges ();//provide save to databasereturn new {success = true, Message = "Saved successfully!" " }; } catch (Exception ex) {return new {success = false, Message = "Save failed! " }; }}
An object with the same key already exists in the Objectstatemanager. Objectstatemanager cannot track multiple objects with the same key