[英]in Parallel.ForEach : The underlying provider failed on Open. with EF5
这段代码有时可以用于某些项目,但是在尝试处理更多项目时它总是失败,而我会得到这个错误: {"The underlying provider failed on Open."}
异常
List<Recon> scenarioAll = db.Transactions
.Where(t => t.SrcObjTyp == "13")
.Select(t => t.Recon).ToList();
//db.Transactions.Where(t => t.SrcObjTyp == "13").ToList().ForEach(t => reconsWithType13Trans.Add(t.Recon));
Parallel.ForEach(scenarioAll.Take(100), r =>
{
// ### Exception : {"The underlying provider failed on Open."} here ###
invoices = r.Transactions.SelectMany(t => t.InvoiceDetails).ToList();
CreateFacts(invoices, r/*, db*/).ForEach(f => facts.Add(f));
transactions = r.Transactions.Where(t => !t.SrcObjTyp.Contains("13")).ToList();
DistributeTransactionOnItemCode(transactions, facts);
Console.WriteLine(i += 1);
});
facts.ForEach(f => db.ReconFacts.Add(f));
db.SaveChanges();
我认为issus是同时访问数据库的多个进程,是否可以通过这种方式允许EF被多个进程查询?
还有一种方法可以将所有内容加载到内存中,以便在访问Recon
的子级时像r.Transactions.SelectMany(t => t.InvoiceDetails).ToList();
一切都会在内存中而不访问底层数据库吗?
我应该使用哪种解决方案?您认为哪种方法最好?
您的问题是您有多个线程试图延迟加载。 尝试将您的负载查询替换为...
List<Recon> scenarioAll = db.Transactions
.Where(t => t.SrcObjTyp == "13")
.Select(t => t.Recon)
.Include(r => r.Transactions.Select(t => t.InvoiceDetails))
.ToList();
http://msdn.microsoft.com/zh-CN/library/gg671236(v=vs.103).aspx
通常来说,如果您依赖于延迟加载,那就错了。
另外,鉴于您可能不需要交易...您可以这样做...
var query = = db.Transactions
.Where(t => t.SrcObjTyp == "13")
.Select(t => t.Recon);
var scenarioAll = query.ToList();
var invoicesByReconIdQuery = from r in query
from t in r.Transactions
from i in t.InvoiceDetails
group i by r.Id into g
select new { Id = g.Key, Invoices = g.ToList() };
var invoicesByReconId = invoicesByReconIdQuery.ToDictionary(x => x.Id, x => x.Invoices);
Parallel.ForEach(scenarioAll.Take(100), r =>
{
// ### Exception : {"The underlying provider failed on Open."} here ###
var invoices = invoicesByReconId[r.Id];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.