尝试这样的事情:
using System;
using System.Transactions;
using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace StackOverflow.Demos
{
class Program
{
static Database db = DatabaseFactory.CreateDatabase("demo");
public static void Main(string[] args)
{
TransactionOptions options = new TransactionOptions();
options.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead; //see http://www.gavindraper.co.uk/2012/02/18/sql-server-isolation-levels-by-example/ for a helpful guide to choose as per your requirements
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
{
using (IDbConnection connection = db.CreateConnection())
{
connection.Open(); //nb: connection must be openned within transactionscope in order to take part in the transaction
IDbCommand command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "select top 1 status from someTable with(UPDLOCK, ROWLOCK) where id = 1"; //see http://msdn.microsoft.com/en-us/library/aa213026(v=sql.80).aspx
string statusResult = command.ExecuteScalar().ToString();
if (!statusResult.Equals("closed",StringComparison.OrdinalIgnoreCase))
{
command.CommandType = CommandType.Text;
command.CommandText = "update someTable set status='closed' where id = 1";
}
scope.Complete();
}
}
}
}
}
附言。通常,建议您使用存储过程而不是硬编码的 SQL,就像我在上面所做的那样 - 如果您可以将所有逻辑推送到存储过程中,这样您只需调用 proc 并且数据库中处理的所有逻辑都这样.
在上面的示例中,您会注意到命名空间:
Microsoft.Practices.EnterpriseLibrary.Data;
那是因为我倾向于使用 MS 的企业库中的数据块,它为您提供了 OOTB 库之上的大量功能。如果您有兴趣,可以在此处阅读更多信息:http: //msdn.microsoft.com/library/cc467894.aspx