what's the best practice to attach a entity object which is detached from anthoer ObjectContext? -
as mentioned in title, how many methods available?
i have case: entity object 1 objectcontext, , detach entity obejct ojbectcontext object, , return it.
later, if make changes on object, , want save changes database. think should write this, right? (well, works me.)
public url getoneurl() { url u; using(servicesentities ctx = new servicesentities()) { u = (from t in ctx.urls select t).firstordefault<url>(); ctx.detach(u); } return u; } public void savetodb(url url) { using(servicesentities ctx = new servicesentities()) { var t = ctx.getobjectbykey(_url.entitykey) url; ctx.detach(t); ctx.attach(url); ctx.objectstatemanager.changeobjectstate(url, system.data.entitystate.modified); ctx.savechanges(); } } url url = getoneurl(); url.ursstring = "http://google.com"; //i change content. savetodb(url);
or
public void savetodb(url url) { using(servicesentities ctx = new servicesentities()) { var t = ctx.getobjectbykey(_url.entitykey) url; t = url; //this make t.urlstring becomes "http://google.com" ctx.applycurrentvalues<url>("urls", t); ctx.savechanges(); } }
this way works me.
the first way generate sql statement update columns of url table, second method provide sql script update "urlstring" columns.
both of them have retrieve temp entity object database 't' in above code.
are there other methods achieve purpose? or other better method know it? or official solution topic?
many thanks.
i don't understand first example. why first entity objectcontext
? not needed because have created new instance of context. can use:
public void savetodb(url url) { using(servicesentities ctx = new servicesentities()) { ctx.attach(url); ctx.objectstatemanager.changeobjectstate(url, system.data.entitystate.modified); ctx.savechanges(); } }
in second example can call:
public void savetodb(url url) { using(servicesentities ctx = new servicesentities()) { var t = ctx.getobjectbykey(_url.entitykey) url; // ensures old values loaded ctx.applycurrentvalues<url>("urls", url); ctx.savechanges(); } }
now difference between 2 approaches clear. first approach (attach
) not need query db first. second approach (applycurrentvalues
) needs query db first old values.
you can use 2 additional approaches. first extension of former approach. allows defining properties changed. second approach manual synchronization loaded entity. approach doesn't use special methods. set loaded entity's properties required values manually. approach useful if work object graph instead of single entity because ef not able automatically synchronize changes in relations.
Comments
Post a Comment