.net - Reload() not updating EF entity -


i .net mvc practice of getting instantiated class model passed controller has of properties filled in posted form values. handy.

[httppost] public actionresult dotask(mymodel model) 

model arrives id , other properties set posted form data. however, suppose want save model , access additional properties exist in database. need reload model @ point.

db.entry(model).state = entitystate.modified; db.savechanges(); db.entry(model).reload(); //model.relatedmodel empty, other model fields not set post 

i expect reload model entirely database based on id. not happen me. model properties not loaded database. still empty.

edit

i not understand why db.entry(model).reload(); failing me. further reading beginning suggest should dispose of dbcontext after performing save , reloading model. true?

edit

whoops! have wrong. see when commit changes db.savechanges() overwriting entire model, not properties have been set mvc controller. must have wrong pattern. how apply new values (as passed controller) database without overwriting non-modified properties? turning nube question, guess.

conclusion

as turned out, reload() update expected. problem was overwriting db row when called savechanges on dbcontext using model auto-instantiated controller context , passed parameter controller method. in case overwrote both assigned properties unassigned ones.

i doing select

model = db.models.single(x => x.id == modelid); 

and updating using updatemodel (calling prefix make work)

updatemodel(model, "myprefix"); db.savechanges(); 

if need update selected properties must manually:

db.yourentityset.attach(model); db.entry(model).property(m => m.someproperty).ismodifed = true; // other properties here db.savechanges(); 

after reload work because want reaload model anyway can this:

var dbmodel = db.yourentityset.single(m => m.id == model.id); dbmodel.someproperty = model.someproperty; // other properties here db.savechanges(); 

and dbmodel "reloaded" one. cannot use authomatic approach updatemodel or applying current values because overrides including values not set client - ef doesn't know valid change.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -