gpt4 book ai didi

c# - asp.net mvc项目中如何访问LocalDB

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:56 25 4
gpt4 key购买 nike

我想访问 localDB。我在 sql server 中的连接字符串如下所示

  <connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Tv3-20171226095229.mdf;Initial Catalog=aspnet-Tv3-20171226095229;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

我的 mdf 文件在 app_data 中是这样的

enter image description here
我正在使用以下代码来访问数据库,如下所示:

public static DataSet GetDataSetFromStoredProc(string sql, Dictionary<string, dynamic> dictionary, string _ConnectionString)
{
try
{
using (SqlConnection connection2 = new SqlConnection(_ConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, connection2);

cmd.CommandType = CommandType.StoredProcedure;
foreach (KeyValuePair<string, dynamic> pair in dictionary)
{
cmd.Parameters.AddWithValue(pair.Key, pair.Value);
}
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
}
catch (SqlException err)
{
// Replace the error with something less specific.
// You could also log the error now.
throw new ApplicationException("Data error. " + err.Message.ToString());
}
}

public static DataTable GetDataTableFromStoredProc(string sql, Dictionary<string, dynamic> dictionary, string _ConnectionString)
{
DataSet ds = GetDataSetFromStoredProc(sql, dictionary,_ConnectionString);

if (ds.Tables.Count > 0)
return ds.Tables[0];
return null;
}

现在我正在执行如下函数:

GetDataTableFromStoredProc("down_data", dictionary, System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)

但我遇到如下异常:

Data error. A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details. )

如何解决这个问题??

最佳答案

尝试从连接字符串中删除“Initial Catalog=aspnet-Tv3-20171226095229;”。

关于c# - asp.net mvc项目中如何访问LocalDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47981663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com