gpt4 book ai didi

c# - 在 Parallel.ForEach : The underlying provider failed on Open. 与 EF5

转载 作者:行者123 更新时间:2023-11-30 12:29:13 25 4
gpt4 key购买 nike

此代码有时适用于某些项目,但在尝试处理更多项目时总是失败,我会得到这个:{"The underlying provider failed on 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();

我认为问题是多个进程同时访问数据库是否可以让 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

一般来说,如果您依赖延迟加载,那您就错了。

或者,假设您可能不需要事务...您可以这样做...

 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];
}

关于c# - 在 Parallel.ForEach : The underlying provider failed on Open. 与 EF5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19155621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com