我有一个带有Asp.net 5/Core 1的EF7应用程序。我通常在DI容器中注册DbContext。
services.AddEntityFramework().AddSqlServer()
.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));这是一个小样本,展示了我想要做的事情。
public class MyController : Controller
{
MyDbContext _myDbContext;
public MyController(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
public IActionResult Index()
{
//Just start these and don't wait for them to finish
//We don't care if they succeed or not
Task.Run(() => DoSomeLogging1());
Task.Run(() => DoSomeLogging2());
return View();
}
private void DoSomeLogging1()
{
_myDbContext.Items.ToList();
}
private void DoSomeLogging2()
{
_myDbContext.Items.ToList();
}
}两个DoSomeLoggingX方法都将使用注入控制器的MyDbContext实例。由于这些方法同时运行,所以另一个方法将不可避免地失败。
连接没有关闭。连接的当前状态是连接。
MyDbContext还使用DI获取一些引用,因此即使我想要,也不能直接使用它。
如何并行运行代码,并且仍然能够通过实体框架使用我的数据库?
发布于 2016-04-16 12:20:08
我也面临着这个问题,现在我使用临时解决方案EF 7(核心)创建类似于DBContext的AddTransient。
如果有人能提供更优雅的解决方案,我将不胜感激。有时,我确实需要将即时结果返回给用户,在这种情况下,等待/异步不适合
发布于 2016-04-14 09:25:04
简单的答案是:你不能。EF不是为并行sql执行而做的(我猜永远也不会)。
不那么简单的答案。也许这并不是解决问题的正确方法(“曾”在他的评论中指出了一点),但是如果你需要做这样的日志记录工作,你可以:
发布于 2022-10-19 12:13:44
实现DBContextFactory并将其注入构造函数中。然后为每个线程创建新的上下文。
在这里进行参考检查,使用DbContext工厂(例如用于Blazor)
https://stackoverflow.com/questions/36609339
复制相似问题