如何在asp.net core和ef7中的并行方法中使用注入的DbContext?

编程入门 行业动态 更新时间:2024-10-28 11:23:49
本文介绍了如何在asp core和ef7中的并行方法中使用注入的DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有EF7的Asp 5/Core 1应用程序.我通常在DI容器中注册DbContext.

I have an Asp 5/Core 1 application with EF7. I register the DbContext in the DI container normally.

services.AddEntityFramework().AddSqlServer() .AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));

这是一个小样本,显示我正在尝试做的事情.

Here is a small sample showing what I'm trying to do.

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实例.由于这些方法是同时运行的,因此会同时执行db查询,因此另一个方法总是会失败,

Both DoSomeLoggingX methods will use the MyDbContext instance that was injected to the controller. Since the methods are run at the same time doing db queries at the same time, the other one will invariably fail with

连接未关闭.连接的当前状态是 连接.

The connection was not closed. The connection's current state is connecting.

MyDbContext还使用DI来获取一些引用,因此即使我愿意也无法直接使用它.

MyDbContext also uses DI to get some references so I can't use it directly even if I wanted.

如何并行运行代码,仍然能够通过实体框架使用数据库?

How can I run code in parallel and still be able to use my database through entity framework?

推荐答案

我也遇到了这个问题,现在我使用临时解决方案 EF 7(核心).创建类似AddTransient的DBContext

I also faced with this problem and for now I use my temporary solution EF 7 (Core). Create DBContext like AddTransient

如果有人可以提供更优雅的解决方案,我将不胜感激.有时我真的需要将即时结果返回给用户,在这种情况下,await/async不适合

If someone can provide more elegant solution I will be appreciated. Sometimes I really need to return instant result to user and in such cases await/async does not suit

更多推荐

如何在asp.net core和ef7中的并行方法中使用注入的DbContext?

本文发布于:2023-11-14 03:21:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586073.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   如何在   asp   core   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!