c# - UnitOfWork - Real Transaction -
i expose somethings "real transaction" , "pseudo transaction". think entity framework implements pseudo transaction , i'll tell why.
// partial code // *** transaction scenario *** // objectcontext ctx = new ... ctx.connection.open(); using(var t = ctx.connection.begintransaction()) { var invoice = new invoice{ price=10, customer="myclient"}; ctx.createobjectset<invoice>().addobject(invoice); ctx.savechanges(); // here 've id invoice (i mean identity autoincrement) , can execute business logic basis on id value var client = new client { name="robert", address="some address", idinvoice=invoice.id} ctx.createobjectset<client>().addobject(client); ctx.savechanges(); // persistence t.commit(); // error? t.rollback } // *** pseudo transaction scenario *** // objectcontext ctx = new ... var invoice = new invoice{ price=10, customer="myclient"}; ctx.createobjectset<invoice>().addobject(invoice); // here haven't invoice id (i mean identity autoincrement) , cannot execute business logic basis on id value var client = new client { name="robert", address="some address", idinvoice=invoice.id} // bad: value 0 ctx.createobjectset<client>().addobject(client); // persistence ctx.savechanges();
note ef update id value after savechanges being called , if exist relation between invoice , client object, otherwise nothing works correctly.
so, question is: practice using "real transaction" on unitowwork pattern? why ef let possibility stumble upon bad issue 1 i've shown you?
savechanges
can send multiple commands database, in case send 2 insert
statements - unbatched , 1 after each other. savechanges
wraps statements transcation managed entity framework , cannot control lifetime. starts @ beginning of savechanges
, gets committed or rolled when statements have been sent , right before savechanges
returns. transaction "real". either both insert
s succeed or none.
in many scenarios sufficient , convenient don't have care transaction management.
in special scenario not sufficient , creating , managing own outer transaction correct solution. wouldn't need if customer
had navigation property invoice
. don't, need separate transaction database generated key value , still perform whole operation in transaction.
Comments
Post a Comment