asp.net mvc - LINQ has trouble updating entities from model binding -


i have edit form extjs extjs not relevant problem. on submit, bind form model.

public actionresult edituserhour([bind(include = "id, duration, hourcategoryid, explanation, invoicetypeid, startdate, starttime, ticketid")] userhour userhour) {     if (modelstate.isvalid)     {         try         {             _service.update(userhour);         }         catch (ruleexception ex)         {             ex.copytomodelstate(modelstate, string.empty);         }      }     if (modelstate.isvalid)         return json(new { success = true, redirect = url.action(listaction) });     else         return json(new { success = false, errors = modelstate.todictionary() }); } 

look @ _service.update(userhour); line. between controller , repository service layer don't call repository directly. consider better design mixing data access, validation , business logic in repository.

currently, - not working - method in _service is:

public void update(userhour userhour) {     crmdatacontext c = new crmdatacontext();     c.refresh(refreshmode.keepcurrentvalues, userhour);     c.submitchanges(); } 

i have tried c.attach(...) calls possible , refresh calls, various exceptions attaching object has key exists.

one of possible solutions have encountered retrieving original entity datacontext , set properties, that's far neat solution. second option use formcollection map original entity, avoid using formcollection , prefer model binding due security reasons. besides, cannot imagine model binding incompatible update.

is there possibility of creating userhour in controller model binding, giving identity of userhour updating , store in database? has bugged me day long now.

any appreciated!

if you're using view model or presentation model, you're going have deal of ugly left/right assignment code. there's no way around it. that's nature of dto's. add layer of abstraction, , lot of times they're helpful, have deal consequences.

however, example seems indicate have one-to-one relationship between database , view. can exploit attach(). here's how it.

  • make sure table has timestamp column. without timestamp column, l2s doesn't job of tracking updates.

example:

timestamp column

  • in view, make sure have both id , timestamp hidden properties. you'll need these both of these when reattach object.

example:

@html.hiddenfor(x => x.id) @html.hiddenfor(x => x.timestamp) 
  • in controller or service, attach work.

example:

public void update(userhour userhour) {   var ctx = new crmdatacontext();   ctx.userhours.attach(userhour, true);   ctx.submitchanges(); } 

Comments