且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用EF Core调用存储过程并关闭连接

更新时间:2023-09-11 21:27:46


我想知道是否需要显式关闭 Assign 方法中的数据库连接,否则连接将自动关闭n请求是通过容器结束的吗?

I wanted to know if I need to explicitly close the DB connection in the Assign method or the connection will be automatically get closed on request end by the container?

是否稍后会自动关闭连接都没有关系。按照良好的编程习惯,应该释放分配的资源(创建->处置,打开->关闭等)。

It doesn't matter if the connection will be closed automatically at some later point or not. Following the good programming practices, one should release the allocated resources (Create -> Dispose, Open -> Close etc.).

EF Core内部为需要开放连接的每个操作执行此操作,因此***这样做,例如像这样的

EF Core internally is doing that for each operation which needs open connection, so you'd better do the same, e.g. something like this

await _dbContext.Database.OpenConnectionAsync();
try
{
    var result = await cmd.ExecuteScalarAsync();

    if (result != null)
    {
        return Convert.ToInt32(result);
    }

    return null;
}
finally
{
    _dbContext.Database.CloseConnection();
}