概要:
学习并发的处理,和事物处理。
内容:
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(); // 在这里设断点,可能出现并发
去除更新检测:
[Column(Storage="_UnitPrice",DbType="Money", UpdateCheck = UpdateCheck.Never)]
这样如果发生并发,则默认以最后一次更新为准。
处理并发:
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);//遇到并发,不继续
ctx.SubmitChanges(ConflictMode.ContinueOnConflict);//遇到并发,还是继续
}
catch (ChangeConflictException)
{
foreach (ObjectChangeConflictcc in ctx.ChangeConflicts)//获取并发对象
{
Product p = (Product)cc.Object;
Response.Write(p.ProductID + "<br/>");
cc.Resolve(RefreshMode.KeepCurrentValues);// 放弃原先更新,所有更新以当前更新 为准
cc.Resolve(RefreshMode.KeepChanges); // 原先更新有效,冲突字段以当前更新 为准
cc.Resolve(RefreshMode.OverwriteCurrentValues); // 放弃当前更新,所有更新以原先更新为准
}
}
ctx.SubmitChanges();
事务处理:
LinQto sql在提交更新的时候默认会创建事务,一部分修改发生错误的话其它修改也不会生效:
ctx.Customers.Add(newCustomer { CustomerID = "abcdf", CompanyName = "zhuye" });
ctx.Customers.Add(newCustomer { CustomerID = "abcde", CompanyName = "zhuye" });
ctx.SubmitChanges();
其他处理办法:
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();
}
第二种:
using (TransactionScope scope = new TransactionScope())
{
CreateCustomer(new Customer{ CustomerID = "abcdf",CompanyName = "zhuye" });
CreateCustomer(new Customer{ CustomerID = "abcde",CompanyName = "zhuye" });
scope.Complete();
}