此代码有时会对某些项有效,但在尝试处理更多项时总是会失败,我会得到:{“底层提供程序在Open上失败.”} exception
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/en-us/library/gg671236(v=vs.103).aspx
一般来说,如果您依赖于Lazy Loading,那么你做错了.
或者,鉴于您可能不需要交易……您可以这样做……
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];
}