You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Database.GetDbConnection()丢失连接字符串致二次执行报错

SqlConnection连接字符串未初始化异常问题解决

问题现象

首次运行下方代码时一切正常,但移除注释中的连接字符串设置逻辑后,第二次运行会抛出如下异常:

System.InvalidOperationException HResult=0x80131509 Message=The ConnectionString property has not been initialized.
Source=Microsoft.Data.SqlClient StackTrace: at Microsoft.Data.SqlClient.SqlConnection.PermissionDemand()

涉及代码如下:

public static List<T> RawSqlQueryOfT<T>(string query,MyDbContext db,Func<DbDataReader, T> map,params SqlParameter[] parameters)
{
    var entities = new List<T>();
    using var cn = db.Database.GetDbConnection();
    var cnState = cn.State;
    if(cn.State.Equals(ConnectionState.Closed))
    {
        // if(cn.ConnectionString.Length == 0)
        // {
        //     cn.ConnectionString = GetConnectionString();  // needed the second time
        // }
        cn.Open();
    }
    using var command = cn.CreateCommand();
    command.CommandText = query;
    command.CommandType = CommandType.Text;
    foreach(var param in parameters)
        command.Parameters.Add(param);
    using var result = command.ExecuteReader( );
    while(result.Read())
    {
        var r = map(result);
        entities.Add(r);
    }
    if(cnState == ConnectionState.Closed)
    {
        cn.Close();
    }
    return entities;
}

环境说明

使用的是Microsoft.Data.SqlClient 4.1.0版本

解决方法

恢复注释中的连接字符串判断与设置代码,取消以下代码的注释即可:

if(cn.ConnectionString.Length == 0)
{
    cn.ConnectionString = GetConnectionString();  // needed the second time
}

更新补充

注意不要在cn声明前添加using关键字,否则会导致连接被提前释放,引发其他问题。


内容的提问来源于stack exchange,提问作者Kirsten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 09:10:28