wpf - C# Entity Framework Entity State Modified -
i pretty new c#. trying make user profile database , display in wpf listview in c#, entity framework code-first.
i have managed add , delete profiles database, , display them. got stuck on modifying existing object , after while of trying make work, closest thing got selected object (selected in listview) makes 1 above receive update.
here code "save" button
private void btnsavechanges_click(object sender, routedeventargs e) { using (userscontext ctx = new userscontext()) { user user = ctx.users.find(userstable.selectedindex); if (user != null) { user.name = txtuname.text; user.idnumber = txtidnumber.text; user.department = txtdepartment.text; user.position = txtposition.text; user.username = txtusername.text; user.password = pwbpassword.password; } ctx.entry(user).state = system.data.entity.entitystate.modified; ctx.savechanges(); txtuname.text = ""; txtidnumber.text = ""; txtdepartment.text = ""; txtposition.text = ""; txtusername.text = ""; pwbpassword.password = ""; userstable.itemssource = ctx.users.tolist(); } } }
the problem when select , try update first entry database (the first row in listview), "argumentnullexception unhandled" error/exception.
visual studio indicates error comes from:
ctx.entry(user).state = system.data.entity.entitystate.modified;
also, can't save changes on last row because when select changes saved on row above it.
i appreciate help.
the exception comes from
ctx.entry(user).state = system.data.entity.entitystate.modified;
because did not include line inside null check. if user null, cause exception.
as general problem: not try select record using selectedindex. if have unique key, selected user selecteditem , retrieve user db this:
user user = ctx.users.firstordefault(u => u.id == selecteduser.id);
also there no need change state manually. ef track changes , automatically save if necessary when call ctx.savechanges();
another thing might using more mvvm approach , use view models bind list , bind user textboxes. depending on application design might consider having 1 dbcontext instead of creating new 1 every time save. way not need fetch users database again when save because ef tracks them.
Comments
Post a Comment