我的连接会在 .NET Core 和 EF Core 中自动关闭,还是我需要在执行查询后关闭它们?
Will my connections close automatically in .NET Core and EF Core or do I need to close them after executing my query?
我是 .NET Core 和 EF Core 的新手。
我的数据库 table 中有一个句子,我必须像这样执行(使用 ADO.NET):
using (var command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "<<my sql sentence>>";
context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
....
}
}
我找到了this documentation。
执行查询后是否需要关闭连接?我想我应该这样做(我认为),但我不知道是否有必要,或者它是否会自动关闭。
用完SqlCommand
就够了,剩下的留给Entity framework或ADO.NET。 SQL 个连接使用 connection pooling,这意味着连接保持打开状态,可以被后续查询重用。
更新:
SQL 联系生活在 DbContext
,GetDbConnection()
method's documentation 说,它
Gets the underlying ADO.NET DbConnection
for this DbContext
.
这意味着,DbContext
有一个数据库连接,并且该连接由它管理(包括连接弹性等功能)。释放 DbContext 时,也会释放 SQL 连接。
只是为了补充马丁的回答,
EFCore
使用连接池。
您可以通过多种方式查看实际连接数。
我是 .NET Core 和 EF Core 的新手。
我的数据库 table 中有一个句子,我必须像这样执行(使用 ADO.NET):
using (var command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = "<<my sql sentence>>";
context.Database.OpenConnection();
using (var result = command.ExecuteReader())
{
....
}
}
我找到了this documentation。
执行查询后是否需要关闭连接?我想我应该这样做(我认为),但我不知道是否有必要,或者它是否会自动关闭。
用完SqlCommand
就够了,剩下的留给Entity framework或ADO.NET。 SQL 个连接使用 connection pooling,这意味着连接保持打开状态,可以被后续查询重用。
更新:
SQL 联系生活在 DbContext
,GetDbConnection()
method's documentation 说,它
Gets the underlying ADO.NET
DbConnection
for thisDbContext
.
这意味着,DbContext
有一个数据库连接,并且该连接由它管理(包括连接弹性等功能)。释放 DbContext 时,也会释放 SQL 连接。
只是为了补充马丁的回答,
EFCore
使用连接池。
您可以通过多种方式查看实际连接数。