Summary:
Learn concurrent processing and transaction processing.
Content:
VaR query = from P inctx. products where P. categoryid = 1 select P;
Foreach (var p inquery)
P. unitsinstock = convert. toint16 (P. unitsinstock-1 );
CTX. submitchanges (); // set a breakpoint here, and concurrency may occur.
Remove update Detection:
[Column (storage = "_ unitprice", dbtype = "money", updatecheck = updatecheck. Never)]
In this case, the last update prevails by default when concurrency occurs.
Processing concurrency:
VaR query = from P inctx. products where P. categoryid = 1 select P;
Foreach (var p in query)
P. unitsinstock = convert. toint16 (P. unitsinstock-1 );
Try
{
CTX. submitchanges (conflictmode. failonfirstconflict); // when concurrency occurs, do not continue
CTX. submitchanges (conflictmode. continueonconflict); // when concurrency occurs, continue
}
Catch (changeconflictexception)
{
Foreach (objectchangeconflictcc in CTX. changeconflicts) // gets the concurrent object
{
Product P = (product) CC. object;
Response. Write (P. productid + "<br/> ");
Cc. Resolve (refreshmode. keepcurrentvalues); // discard the original update. All updates are subject to the current update.
Cc. Resolve (refreshmode. keepchanges); // The original update is valid. The conflicting fields are subject to the current update.
Cc. Resolve (refreshmode. overwritecurrentvalues); // discard the current update. All updates are subject to the previous update.
}
}
CTX. submitchanges ();
Transaction processing:
By default, linqto SQL creates transactions when submitting updates. If some modifications are incorrect, other modifications will not take effect:
CTX. Customers. Add (newcustomer {customerid = "abcdf", companyName = "Zhuye "});
CTX. MERs. Add (newcustomer {customerid = "ABCDE", companyName = "Zhuye "});
CTX. submitchanges ();
Other solutions:
If (CTX. connection! = NULL) CTX. Connection. open ();
Dbtransactiontran = CTX. Connection. begintransaction ();
CTX. Transaction = Tran;
Try
{
Createcustomer (new customer {customerid = "abcdf", companyName = "Zhuye "});
Createcustomer (new customer {customerid = "ABCDE", companyName = "Zhuye "});
Tran. Commit ();
}
Catch
{
Tran. rollback ();
}
Private void createcustomer (customerc)
{
CTX. Customers. Add (C );
CTX. submitchanges ();
}
Second:
Using (transactionscope scope = new transactionscope ())
{
Createcustomer (new customer {customerid = "abcdf", companyName = "Zhuye "});
Createcustomer (new customer {customerid = "ABCDE", companyName = "Zhuye "});
Scope. Complete ();
}