【问题标题】:An error occurred while starting a transaction on the provider connection. See the inner exception for details在提供程序连接上启动事务时出错。有关详细信息,请参阅内部异常
【发布时间】:2014-02-13 21:28:51
【问题描述】:

这是我的编码。它显示错误,例如 在提供程序连接上启动事务时出错。有关详细信息,请参阅内部异常。

       DemoEntities db = DemoEntities.CreateNewDemoEntity();
       var query = (from f in db.Product_Table
                    where f.ReportID == reportID && f.StateID == stateID
                    select f);
       foreach(var q in query)
       {
           Custom_Search_Transformation cst = new Custom_Search_Transformation()
           {
               CustomerID = customerID,
               StateID = stateID,
               FullProductID = q.FullProductID
           };
           db.Custom_Search_Transformation.AddObject(cst);
           db.SaveChanges();
       }

【问题讨论】:

  • “详情见内部异常”是有原因的。
  • 我发现了问题 db.SaveChanges();应该在 foreach 循环之外
  • 当然,但是在 SO 问题中,显示内部异常告诉您的内容总是一个好主意。

标签: c# linq entity-framework


【解决方案1】:

db.SaveChanges(); 应该在 foreach 循环之外:

DemoEntities db = DemoEntities.CreateNewDemoEntity();
var query = (from f in db.Product_Table
             where f.ReportID == reportID && f.StateID == stateID
             select f);
foreach(var q in query)
{
    Custom_Search_Transformation cst = new Custom_Search_Transformation()
    {
        CustomerID = customerID,
        StateID = stateID,
        FullProductID = q.FullProductID
    };
    db.Custom_Search_Transformation.AddObject(cst);          
}
db.SaveChanges();

【讨论】:

  • 做了同样的事情,但仍然得到同样的错误。一件事是我在一个线程中运行它
【解决方案2】:

将您的可查询列表设为 .ToList() 它应该可以正常工作。

【讨论】:

  • 有时您必须在每个循环结束时将数据保存到数据库中。如果是这种情况,正如这个答案所解释的那样,“var q in query.ToList”可以解决问题。
  • 我遇到了这个问题,我必须在每次迭代期间保存数据以从记录中获取 ID 以用于第 3 方系统的跟踪目的。在循环之前运行 .ToList() 允许我在不保持事务打开的情况下迭代这些项目,从而使 SaveChanges 调用没有问题。
猜你喜欢
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多