c# - 在 ASP.NET Core 中为每个 SQL 命令打开/关闭数据库

标签 c# postgresql asp.net-core entity-framework-core npgsql

我编写了简单的 ASP.NET Core 应用程序,其中 Controller 注入(inject) MyService(配置为 Scoped),后者又注入(inject) MyDbContext。

在我的 Controller 方法中,我有 2 个数据库查询,我的调试输出如下所示:

 Executing action method...
 Opening connection to database 'shell' on server 'tcp://127.0.0.1:5432'.
 ...
 Closing connection to database 'shell' on server 'tcp://127.0.0.1:5432'.
 Opening connection to database 'shell' on server 'tcp://127.0.0.1:5432'.
 ...
 Closing connection to database 'shell' on server 'tcp://127.0.0.1:5432'.
 Request finished in...

问题是:在每个请求上打开一个新连接是否正确,甚至更多 - 为每个 sql 命令打开一个新连接?它不能建立一次与数据库的连接并重新使用它吗?性能不是更好吗?

PS:我使用带有 npgsql 提供程序的 PostgreSQL

最佳答案

就像其他人提到的那样。连接池是您的 friend 。

打开和关闭完全没问题。

https://stackoverflow.com/a/4439434/3799142

关于c# - 在 ASP.NET Core 中为每个 SQL 命令打开/关闭数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147437/

相关文章:

ruby-on-rails - 了解 "attribute_will_change!"方法

sql - 如何获取 postgresql 9.5 中特定模式中存在的所有表的表行数?

c# - 在 ASP.NET 5 (MVC6) 中请求 BinaryRead

c# - 在 VBScript 中使用 DLL

c# - 为什么在 Java(和其他)中大写类名只是一个建议而不是规则?

c# - ParallelOptions.MaxDegreeOfParallelism不做任何事情

regex - Postgres : Extract the last substring in a string

c# - ASP .NET Webhook 接收器

c# - Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT 中间件 C# .NET Core 2.2

asp.net-core - ASP.NET Core 中的环境变量有什么区别?