[英]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.