asp.net mvc - Not Able to get entity data from database -


i trying edit user entity.

when password field left blank, want password remain same in database. if users enters new password, want update it.

i tried password on database in case password field left blank. following error:

an object same key exists in objectstatemanager. objectstatemanager cannot track multiple objects same key.

public actionresult edit([bind(include = "id,nombre,apellido,password,repeatpassword,idrol,email,activo,resetpassword,username, imagen, oldpassword")] usuario usuario) {     try {         string oldpassword = db.usuarios.find(usuario.id).password;         var password = "";         if (string.isnullorempty(usuario.password) && string.isnullorempty(usuario.repeatpassword)) {              password = oldpassword;              if (modelstate.containskey("password")) modelstate["password"].errors.clear();             if (modelstate.containskey("repeatpassword")) modelstate["repeatpassword"].errors.clear();         } else {             password = usuario.repeatpassword;             password = encryption.encryptpassword(password);         }          if (modelstate.isvalid) {             usuario.password = password;             usuario.repeatpassword = password;             db.entry(usuario).state = system.data.entity.entitystate.modified;             db.savechanges();              sesion.messages.add(new usermessage() {                 type = messagetype.success, message = "el usuario se editó exitosamente"             });             return redirecttoaction("index");         }         viewbag.roleslist = new selectlist(db.roles, "id", "nombre");         return view(usuario);     } catch (exception ex) {         log.logexception(ex, controllercontext);         return redirecttoaction("index");     } } 

any idea?

if want update existing element should follow pattern:

1) element repository using id

2) update modified fields of obtained element

3) save element

this way entity framework not try create new element same id.

in case should replace

string oldpassword = db.usuarios.find(usuario.id).password; ... 

with

var olduser = db.usuarios.find(usuario.id); olduser.password = ...<new values>... db.entry(olduser).state = system.data.entity.entitystate.modified; //i thinks not required... db.savechanges(); 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -