我正在尝试将TransactionScope与Npgsql提供程序一起使用。 我在旧问题(provider for PostgreSQL in .net with support for TransactionScope)中发现Npgsql尚未支持它。 现在,大约5年后,Npgsql是否支持TransactionScope? 我使用Npgsql 3.0.3并使用以下代码为自己做了一个测试:
using (var scope = new TransactionScope())
{
using(var connection = new Npgsql.NpgsqlConnection("server=localhost;user id=*****;password=*****database=test;CommandTimeout=0"))
{
connection.Open();
var command = new NpgsqlCommand(@"insert into test.table1 values ('{10,20,30}', 2);");
command.Connection = connection;
var result = command.ExecuteNonQuery();
// scope.Complete(); <-- Not committed
}
}
任何人都可以确认Npgsql不支持TransactionScope吗?
编辑#1 在确认Npgsql对TransactionScope的支持后,我发现你需要确保在PostgreSQL配置中启用Distribuited Transaction,检查 postgres.conf中的 max_prepared_transactions 参数/ em>文件(记得重新启动服务器)。
编辑#2 我在我的服务器上启用了Distribuited Transaction,但现在我使用带有Npgsql的TransactionScope时出错了。 这是我的代码:
using (var sourceDbConnection = new NpgsqlConnection(SourceConnectionString))
using (var destinationDbConnection = new NpgsqlConnection(DestinationConnectionString))
using (var scope = new TransactionScope())
{
sourceDbConnection.Open();
destinationDbConnection.Open();
Logger.Info("Moving data for the {0} table.", TableName.ToUpper());
var innerStopWatch = new Stopwatch();
innerStopWatch.Start();
foreach (var entity in entities)
{
var etlEntity = new EtlInfoItem
{
MigratedEntityId = category.RowId,
ProjectId = category.ProjectId,
ExecutionDatetime = DateTime.Now
};
// Insert into the destination database
var isRowMigrated = InsertEntity(entity, DestinationSchema, destinationDbConnection);
if (isRowMigrated)
{
// Update the ETL migration table
InsertCompletedEtlMigrationEntity(etlEntity, EtlSchema, sourceDbConnection);
}
else
{
// Update the ETL migration table
InsertFailedEtlMigrationEntity(etlEntity, EtlSchema, sourceDbConnection);
}
}
Logger.Info("Data moved in {0} sec.", innerStopWatch.Elapsed);
Logger.Info("Committing transaction to the source database");
innerStopWatch.Restart();
scope.Complete();
innerStopWatch.Stop();
Logger.Info("Transaction committed in {0} sec.", innerStopWatch.Elapsed);
}
当TransactionScope退出作用域时(退出using语句时),我得到一个Null Reference Exception,其中包含以下堆栈跟踪: 服务器堆栈跟踪: 在Npgsql.NpgsqlConnector.Cleanup() 在Npgsql.NpgsqlConnector.Break() 在Npgsql.NpgsqlConnector.ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode,Boolean returnNullForAsyncMessage) 在Npgsql.NpgsqlConnector.ReadExpectingT ......... 它是随机发生的。
答案 0 :(得分:3)
Npgsql确实支持TransactionScope,并且已经这么做了很长一段时间。但是,至少目前,为了使您的连接参与TransactionScope,您必须:
Enlist=true
,或看看周围的Npgsql unit tests以获取一些例子。