问题描述
对于Asp.net Core应用程序,我们必须使用哪一个? AddDbContext
还是AddDbContextPool
?根据EF Core文档,AddDbContextPool
具有高性能,但是默认的Asp.net Core项目模板使用AddDbContext
.
For Asp.net Core apps, which one do we have to use? AddDbContext
or AddDbContextPool
? According to EF Core documentation, AddDbContextPool
provides high performance but the default Asp.net Core project templates use AddDbContext
.
推荐答案
答案在这里(在"DbContext池"下): https://docs.microsoft.com/zh-cn/ef/core/what-is-new/ef- core-2.0#dbcontext-pooling
The answer is here (under "DbContext pooling"): https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.0#dbcontext-pooling
DbContext
不是线程安全的.因此,您无法将同一DbContext
对象同时用于多个查询(奇怪的事情会发生).通常的解决方案是每次需要一个新的DbContext
对象.这就是AddDbContext
的作用.
DbContext
is not thread-safe. So you cannot reuse the same DbContext
object for multiple queries at the same time (weird things happen). The usual solution for this has been to just create a new DbContext
object each time you need one. That's what AddDbContext
does.
但是,在完成先前的查询之后,重用DbContext
对象没有任何问题.这就是AddDbContextPool
所做的.它使多个DbContext
对象保持活动状态,并为您提供了一个未使用的对象,而不是每次都创建一个新对象.
However, there is nothing wrong with reusing a DbContext
object after a previous query has already completed. That's what AddDbContextPool
does. It keeps multiple DbContext
objects alive and gives you an unused one rather than creating a new one each time.
您要使用哪一个取决于您.两者都会起作用.池化可以提高性能.但是文档警告说,如果您在DbContext
类中使用了不应在查询之间共享的任何私有属性,则不应使用它.我想那是非常罕见的,所以在大多数情况下合并应该是合适的.
Which one you use is up to you. Both will work. Pooling has some performance gains. However the documentation warns that if you use any private properties in your DbContext
class that should not be shared between queries, then you should not use it. I imagine that's pretty rare though, so pooling should be appropriate in most cases.
这篇关于AddDbContext或AddDbContextPool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!