c# - Unable to edit db entries using EFCore, EntityState.Modified: "Database operation expected to affect 1 row(s) but actually affected 0 row(s)." -


i'm using identity core 1.0 asp.net mvc core 1.0 , entity framework core 1.0 create simple user registration system this article starting point, , trying add user roles. can add user roles, i'm unable edit them. here edit action in rolescontroller:

    [httppost]     [validateantiforgerytoken]     public iactionresult edit(identityrole role)     {         try         {             _db.roles.attach(role);             _db.entry(role).state = microsoft.entityframeworkcore.entitystate.modified;             _db.savechanges();             return redirecttoaction("index");         }         catch (exception ex)         {             console.writeline(ex);             return view();         }     } 

here form in corresponding view:

@model microsoft.aspnet.identity.entityframework.identityrole @{     viewbag.title = "edit"; }  <h2>edit role</h2> <hr /> @using (html.beginform()) {     @html.antiforgerytoken()     @html.validationsummary(true)     @html.hiddenfor(model => model.id)     <div>role name</div>     <p>@html.textboxfor(model => model.name)</p>     <input type="submit" value="save" /> } 

the new role name not save database, , following exception: database operation expected affect 1 row(s) affected 0 row(s). data may have been modified or deleted since entities loaded.

i able use exact code (with microsoft.aspnet.identity.entityframework dependency instead of entityframeworkcore) edit database entries using ef 7, identity 3, etc.

any thoughts on why code not allow database entries modified?

unless there hidden exception hiding behind dumb random exception, reason stated in exception.

check id on role object receive on edit action , try lookup id in database. exception message see states that, expecting find row matching id of object attached, not, failing update, since not locate matching row update it.

edit :

you attaching entity twice, remove call .attach(role) , keep line below sufficient add object tracking context in modified state.

//_db.roles.attach(role); //remove line !. _db.entry(role).state = microsoft.entityframeworkcore.entitystate.modified; 

beware setting state of entry modified update property values upon calling .savechanges(), in case want update properties refer this answer.

if doesn't solve problem, please check inner exceptions might've missed. exception messages don't make sense , mask real problem might able find in inner exception.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -