我有一个带有EF7的Asp.net 5 / Core 1应用程序。我通常在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来获取一些引用,所以即使我想要也不能直接使用它。
如何并行运行代码并仍然可以通过实体框架使用我的数据库?
答案 0 :(得分:1)
我也面临这个问题,现在我使用我的临时解决方案 EF 7 (Core). Create DBContext like AddTransient
如果有人能提供更优雅的解决方案,我将不胜感激。有时我真的需要将即时结果返回给用户,在这种情况下,await / async不适合
答案 1 :(得分:0)
简单回答:你不能。 EF不是为并行sql执行而做的(我猜也是如此)。
不太简单的答案。可能这不是解决问题的正确方法(@Tseng在他的评论中提到了一点),但是如果你需要做类似的日志记录,你可以: