Dapper和EF Core事务失败,错误为SqlConnection不支持并行事务

时间:2019-12-19 07:29:41

标签: c# entity-framework .net-core entity-framework-core dapper

我开始将EF Core与Dapper结合使用,并在调用context.SaveChanges()时尝试同时在TransactionScope中使用它们时,出现错误public void someMethodToSetJob() { final String cronTabSchedule = "0 0 3 ? * MON-FRI *"; final Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR_OF_DAY, 3); cal.set(Calendar.SECOND, 0); final Calendar expiry = Calendar.getInstance(); expiry.set(Calendar.MONTH, 11); expiry.set(Calendar.DATE, 31); expiry.set(Calendar.YEAR, 9999); expiry.set(Calendar.SECOND, 0); processBackgroundProcessCheck(cal.getTime(), cronTabSchedule, expiry.getTime()); } 代码如下:

SqlConnection does not support parallel transactions.

如何在单个transactionscope中成功地混合使用EF Core和Dapper操作?

3 个答案:

答案 0 :(得分:1)

对于任何遇到相同问题的人,我都找到了解决方案。

<property>
   <name>fs.file.impl</name>
   <value>org.apache.hadoop.fs.LocalFileSystem</value>
   <description>The FileSystem for file: uris.</description>
</property>

<property>
   <name>fs.hdfs.impl</name>
   <value>org.apache.hadoop.hdfs.DistributedFileSystem</value>
   <description>The FileSystem for hdfs: uris.</description>
</property> 

答案 1 :(得分:1)

在dotnet core 3.1中,您可以尝试以下操作。但它仅适用于关系数据库。

context.Database.UseTransaction((DbTransaction)transaction);
context.SaveChanges();
transaction.Commit();

答案 2 :(得分:-1)

下面,我使您的代码更易于阅读**。

为什么要混合与数据库通信的方式

我已发表评论,这将帮助您确定实际问题所在。

ps原因是您先打开一个交易,然后再打开另一个交易...  using (IDbTransaction transaction是未平仓交易,_dbContext.SaveChanges();也是交易。

public class TestController : ControllerBase
{
    private readonly MyDbContext _dbContext;
    private readonly IDbConnection _dbConnection;

    public TestController(MyDbContext dbContext, IDbConnection dbConnection)
    {
        _dbContext = dbContext;
        _dbConnection = dbConnection;
    }

    public void Test2()
    {
        var client = new Client();
        client.ClientId = 3;
        client.Name = "New Client 3";

        //is the correct way to attach and entrity mark as modified.
         _dbContext.Entry<Client>(client).State = EntityState.Modified;
         _dbContext.SaveChanges();

        var clients = new List<Client>();
        clients.Add(new Client { ClientId = 1, Name = "New Client 1", });
        clients.Add(new Client { ClientId = 2, Name = "New Client 2", });
        clients.Add(new Client { ClientId = 4, Name = "New Client 4", });

        using (IDbTransaction transaction = _dbConnection.BeginTransaction())
        {
            string sql = "UPDATE Client SET Name = @Name WHERE ClientId = @ClientId;";
            //is this the correct way to call dapper
            _dbConnection.Execute(sql, clients, transaction: transaction);
            transaction.Commit();
        }
    }
}