【问题标题】:EF6 : Multiple transactions at the same timeEF6:同时进行多个事务
【发布时间】:2015-12-23 10:34:11
【问题描述】:

我的项目有两个部分:一个收集一些数据的 Powershell 脚本和一个 ASP.NET 4.5 MVC 应用程序(使用 Entity Framework 6.1.3),它接收数据(作为文件)并将它们集成到数据库中。大约有 1500 个文件将发送到 ASP.NET 应用程序。

我需要使用事务:如果将数据添加到数据库时发生错误,则无需添加任何内容(回滚)。添加这个功能没有问题。但似乎当一个事务开始时,另一个事务在第一个事务提交或回滚之前无法开始。这很糟糕,因为我的 1500 个文件必须一个一个地等待添加,并且由于集成时间为 +/- 5 分钟,因此需要太多时间。

我不知道我在哪里犯了错误。这是我的代码的样子:

public bool JsonToDB(dynamic data)
{
    using (MyEntities context = new MyEntities())
    {                
        context.Database.CommandTimeout = 300;
        context.Configuration.AutoDetectChangesEnabled = false;
        context.Configuration.ValidateOnSaveEnabled = false;

        using (var transaction = context.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
        {
            try
            {           
                // DB integration from the file provided by the Powershell script.

                context.SaveChanges();

                transaction.Commit();
                transaction.Dispose();              

                return true;
            }
            catch (Exception e)
            {
                // Error management.

                transaction.Rollback();                        
                transaction.Dispose();

                return false;
            }
        }
    }
}

public Task FileIntegration(string fileDirectory, string fileName)
{
    return Task.Factory.StartNew(() =>
    {
        try
        {
            string fileContent = System.IO.File.ReadAllText(fileDirectory + "JSON/" + fileName, Encoding.ASCII);

            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

            dynamic data = serializer.Deserialize(fileContent, typeof(object));

            if (JsonToDB(data))
            {                    
                System.IO.Directory.Move(fileDirectory + "JSON/" + fileName, fileDirectory + "JSON/Success/" + fileName);               
            }
            else
            {
                System.IO.Directory.Move(fileDirectory + "JSON/" + fileName, fileDirectory + "JSON/Error/" + fileName);
            }
        }
        catch(Exception e)
        {
            System.IO.Directory.Move(fileDirectory + "JSON/" + fileName, fileDirectory + "JSON/Error/" + fileName);
        }
});
}

[HttpPost]
[AllowAnonymous]
public ActionResult Receive(HttpPostedFileWrapper file)
{
    try
    {
        file.SaveAs(Server.MapPath("~") + "/Files/JSON/" + file.FileName);

        HostingEnvironment.QueueBackgroundWorkItem(ct => {
            return FileIntegration(Server.MapPath("~") + "/Files/", file.FileName);
        });
    }
    catch (Exception e)
    {
        return new HttpStatusCodeResult(400, "Unable to save the JSON file. Detailed error: " + e.Message);
    }

    return new HttpStatusCodeResult(200, "OK");
}

我也尝试使用 SaveChangesAsync 方法来保存更改(https://stackoverflow.com/a/28133913)但出现错误:

提交数据库事务时报错,但无法确定事务在数据库服务器上是成功还是失败。

你有什么想法可以帮助我解决这个问题吗?

提前致谢。

编辑 :更清楚一点:指令context.SaveChanges(); 不能同时执行多个事务。要应用其更改,事务必须等待其他更改应用程序的结束。我想要的是能够让多个方法实例在不等待的情况下保存它们的更改。数据库集成仅包括数据库中的插入和删除(无更新)。

【问题讨论】:

    标签: c# asp.net asp.net-mvc entity-framework transactions


    【解决方案1】:

    您需要使用TransactionScope 类。这是一个例子

    using (TransactionScope scope = new TransactionScope())
    {
        //Do something with context1
        //Do something with context2
    
        //Save and discard changes
        context1.SaveChanges();
    
        //Save and discard changes
        context2.SaveChanges();
    
        //if we get here things are looking good.
        scope.Complete();
    }
    

    【讨论】:

    • 你有相关的msdn文档吗? :)
    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多