在 ALinq 中使用事务
2011-12-04 10:05 麦舒 阅读(660) 评论(1) 编辑 收藏 举报下面是 ALinq 使用事务的例子,比较简单,直接上代码:
var db = new AccessNorthwind("C:/Northwind.mdb") { Log = Console.Out };
db.DoTransaction(delegate()
{
db.Customers.Update(o => new Customer { CompanyName = "XXXX" }, o => o.CustomerID == "kkkkk");
db.Customers.Delete(o => o.CustomerID == "aaaaa");
});
public static partial class Utility
{
public static void DoTransaction(this DataContext dc, Action func)
{
dc.Connection.Open();
var tran = dc.Connection.BeginTransaction();
dc.Transaction = tran;
try
{
func();
tran.Commit();
}
catch
{
tran.Rollback();
throw;
}
finally
{
dc.Connection.Close();
}
}
}
有朋友问到,如果是用 SQL 的,怎么写, OK,再上一个 SQL 的例子:
var str = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Northwind.mdb";
new OleDbConnection(str).DoTransaction(delegate(IDbCommand command)
{
command.CommandText = @"UPDATE [Customers]
SET [CompanyName] = @p0
WHERE [CustomerID] = @p1";
command.Parameters.Add(new OleDbParameter("@p0", "XXXXX"));
command.Parameters.Add(new OleDbParameter("@p1", "kkkkk"));
command.ExecuteNonQuery();
command.CommandText = @"DELETE FROM [Customers] WHERE [CustomerID] = @p0";
command.Parameters.Add(new OleDbParameter("@p0", "aaaaa"));
command.ExecuteNonQuery();
});
public static partial class Utility
{
public static void DoTransaction(this DataContext dc, Action func)
{
dc.Connection.Open();
var tran = dc.Connection.BeginTransaction();
dc.Transaction = tran;
try
{
func();
tran.Commit();
}
catch
{
tran.Rollback();
throw;
}
finally
{
dc.Connection.Close();
}
}
}