11 c# linq sql-server stored-procedures linq-to-sql
我有一个C#.net winform程序,它运行SQL Server数据库.我正在使用LINQ-to-SQL.是否可以使用LINQ-to-SQL将调用回滚到程序中的事务内的一个或多个存储过程?
最初我认为管理存储过程中的事务是有意义的,但如果我需要回滚多个存储过程调用作为单个事务的一部分,则需要在我的C#程序中完成.
有人能指出我如何做到这一点或提供一些替代方案的代码片段吗?
Mar*_*ell 15
另一个替代方案DbTransaction是TransactionScope- 这提供了一个更简单的编程模型,并且可以扩展到多个同时的数据库和其他提要(通过DTC) - 但是以连接上的少量开销为代价.它曾经是更多的开销,但在SQL2005等之下它将使用"LTM"直到您开始跨越多个连接 - 所以单个操作通常非常便宜:
using (TransactionScope tran = new TransactionScope())
using (FooDataContext ctx = new FooDataContext())
{
// your work with ctx
// ...
// other work involving connections etc
// ...
tran.Complete();
}
Run Code Online (Sandbox Code Playgroud)
非常简单;-p您还应该能够使事务更精细(仅通过几个查询)或更简单地包含.大多数现有代码将自动登记在事务范围内,使得很容易适应现有代码.
有关TransactionScope(以及.NET中的常规事务)的更多信息,请参见此处.
And*_*llo -1
虽然我没有使用存储过程,但你可以有类似的东西:
public Response<SomeObject> SaveSomething(Object yourObject)
{
DbTransaction dbTransaction = null;
try
{
using (DataContext context = new DataContext())
{
//Creates a new DB transaction
if (context.Connection.State == System.Data.ConnectionState.Closed)
{
context.Connection.Open();
}
dbTransaction = context.Connection.BeginTransaction(System.Data.IsolationLevel.Serializable);
context.Transaction = dbTransaction;
context.SaveYourObject(yourObject);
//Commit the transaction
dbTransaction.Commit();
response.ResponseObject = yourObject;
response.Messages.AddSuccessfulSave("Saved!");
}
}
}
catch (ChangeConflictException cex)
{
if (dbTransaction != null) dbTransaction.Rollback();
response.Errors.AddConcurrencyError();
response.IsSuccessful = false;
}
catch (SqlException sqlEx)
{
if (dbTransaction != null) dbTransaction.Rollback();
if (sqlEx.Class == 14 && (sqlEx.Number == 2601 || sqlEx.Number == 2627)) //Duplicated key
{
response.Errors.Add(new Error
{
Name = "Duplicate item",
Description = "This object already exists."
});
ExceptionPolicy.HandleException(sqlEx, SERVICE_EXCEPTION_POLICY);
response.IsSuccessful = false;
}
else //other SQL errors
{
response.Errors.AddSavingError("Your object", yourObjectId);
ExceptionPolicy.HandleException(sqlEx, SERVICE_EXCEPTION_POLICY);
response.IsSuccessful = false;
}
}
Run Code Online (Sandbox Code Playgroud)