2012年12月6日 星期四
{C#} Transaction-Linq
//此例可直接運用 context.SubmitChanges();自動執行Transaction,
此側僅供自訂Transaction code參考用
using (var context = new ServiceDataContext())
{
try
{
context.Connection.Open();
context.Transaction = context.Connection.BeginTransaction();
var query = context.tableA.Where(s => s.DocId == DocId).ToList();
if (query.Count > 0)
{
context.tableA.DeleteAllOnSubmit(query);
context.SubmitChanges();
}
context.tableA.InsertOnSubmit(pNewItemA);
context.SubmitChanges();
var queryTT = context.tableB.Where(s => s.DocId ==DocId).ToList();
if (queryTT.Count > 0)
{
context.tableB.DeleteAllOnSubmit(queryTT);
context.SubmitChanges();
}
context.tableB.InsertOnSubmit(pNewItemB);
context.SubmitChanges();
context.Transaction.Commit();
return "Successful";
}
catch (Exception ex)
{
context.Transaction.Rollback();
return ex.Message;
}
}
註記:
1.Linq2SQL will use an implicit transaction. If all of your updates are done within a single Submit, you may not need to handle the transaction yourself.
當只執行一SubmitChanges()時,會自動啟動Transaction 機制
故如非同一context 時,才需自訂Transaction
參考資料:
http://blog.darkthread.net/blogs/darkthreadtw/archive/2009/06/12/3037.aspx
http://stackoverflow.com/questions/542525/transactionscope-vs-transaction-in-linq-to-sql
http://72.15.222.47/post-2008-05-14-transaction-in-linq-to-sql.aspx
//Update之Transaction 相關
http://72.15.222.47/post-2009-07-14-linq-to-sql-research1.aspx
http://blog.miniasp.com/post/2008/05/Resolve-LINQ-to-SQL-Change-Conflict-Exception.aspx