The new entity framework and concurrency are used. refer to the following books and materials.
Entity Framework 4.0 recipes a problem-solution Approach
ISBN-13 (pbk): 978-1-4302-2703-8
ISBN-13 (electronic): 978-1-4302-2704-5
Http://apress.com/book/view/1430227036
The procedure is as follows:
Model Creation
After adding the ado.net entity model, add the timestamp concurrency control timestamp as follows:
Note:
Concurrency Control does not have to add a timestamp. If you do not add a timestamp, you need to set the concurrency mode of the field updated each time to fixed. Generally, it is easier to add a timestamp.
Generate Database
This is a newly added function of vs2010. vs2008 SP1 does not have this function and is easy to use. It can be designed from the model.
As shown above, you can right-click the model to generate a database script. However, the generated script has some problems in processing the timestamp field, the field generated by the default model is not of the timestamp Database Type [it should be able to be modified in the ssdltosql10.tt file without trial]. You can add an SQL file as follows:
Alter table demoset drop column [timestamp] alter table demoset add [timestamp] timestamp notNull
When updating the database from the model, you only need to run the generated SQL script first, and then run the script.
Concurrent processing
Using (Testcontainer context = New Testcontainer ()){ // Add a new record Demo d = New Demo () {name =" A ", Phone =" 123 "}; Context. demoset. addobject (d); context. savechanges (); // Use SQL to execute an update to simulate concurrency D = context. demoset. First (); context. executestorecommand (@" Update demoset set phone = '000000' where id = @ P0 ", New Object [] {D. id }); /// Handle concurrent conflicts Try {D. Phone =" 321 "; /// You can also use the last update method as the standard. The following two lines are blocked: /// Context. demoset. mergeoption = mergeoption. preservechanges; /// D = context. demoset. First (P => P. ID = D. id ); Context. savechanges (); console. writeline (" No concurrency exception. ");} Catch (Optimisticconcurrencyexception ){ Try {Context. Refresh (refreshmode. clientwins, d); context. savechanges ();} Catch (Optimisticconcurrencyexception ){ // When there are a large number of users, the processing will be instantly updated by others, and the processing will continue. }} // Clear the database D = context. demoset. First (); context. deleteobject (d); context. savechanges ();}