c# - Why don't I get an EF5 Concurrency Error? -
in database i'm working on company keeps track of order numbers each regional office. have table named [company] has single record each regional office. table has field holds next available order number office. orders created in single [order] table. realized possible more 1 user @ given office ask new order @ same time. have set optimistic concurrency. [company] table has column named rowmodtracker used concurrency purposes (see images @ bottom properties in ef , sql).
in code below, record regional office, increment field has order number , put copy in local variable. save off table. expect if 2 users hit method @ same time first user save off valid order number. expect second user save off optimistic concurrency error , null should returned (which causes prompt asks them try again). users tell me few times in last 8 months have indeed gotten orders same order number. no messages , no errors happen until later in process when go save order , unique constraint on order number violated.
i don’t understand fundamental ef concurrency checking , i’m hoping can show me light. wrote test version of getnextordernumberandupdate wrapped second using context around first , did indeed generate expected concurrency error. doesn't seem happen when 2 different clients it.
private int? trytogetnextordernumber() { int? order_number; bool keep_trying = true; while (keep_trying) { order_number = _entitymanager.getnextordernumberandupdate(); if (order_number != null) return order_number; keep_trying = keeptryingforordernumberprompt(); } return null; } public int? getnextordernumberandupdate() { try { using (var db_context = new hotentities(entityconnectionstring)) { var hss_company = db_context.companies.find(hsscompanyinuse.hsscompanyid); int? next_order_num = ++hss_company.nextordernum; db_context.savechanges(); return next_order_num; } } catch (dbupdateconcurrencyexception) { return null; } catch (exception ex) { return null; //actual code puts out alert } }
i using entity framework 5 , sql server 2008 r2 .net 4.5.
edit
the test version looked this, i've elided try/catch stuff same above
//test force failure using (hotentities test_context = new hotentities(entityconnectionstring)) { var test_hss_company = test_context.companies.find(hsscompanyinuse.hsscompanyid); int? test_next_order_num = ++test_hss_company.nextordernum; //======= normal code ============ using (var db_context = new hotentities(entityconnectionstring)) { var hss_company = db_context.companies.find(hsscompanyinuse.hsscompanyid); var next_order_num = ++hss_company.nextordernum; db_context.savechanges(); return next_order_num; } //======= end normal code ============ test_context.savechanges(); //dbupdateconcurrencyexception exception thrown here } //end test using
Comments
Post a Comment