C#使用Microsoft.Data.SqlClient连接SQL Server时抛出InvalidOperationException
问题描述
我正在开发一个需向SQL Server数据库写入数据的项目,项目变量采用西班牙语命名。
连接字符串配置
<configuration> <connectionStrings> <add name="conexionServidorHotel" connectionString="Data Source=DESKTOP-QG08OQQ\SQLEXPRESS;Initial Catalog=Script_RESORTSUNED;Integrated Security=True;"/> </connectionStrings> </configuration>
C#代码实现
using Entidades; using System.Configuration; using System.Data; using Microsoft.Data.SqlClient; using System.Diagnostics; namespace AccesoDatos { public class HotelAD { private string cadenaConexion; public HotelAD() { cadenaConexion = ConfigurationManager.ConnectionStrings["conexionServidorHotel"].ConnectionString; } public bool RegistrarHotel(Hotel NuevoHotel) { bool hotelregistrado = false; try { SqlConnection conexion; SqlCommand comando = new SqlCommand(); using (conexion = new SqlConnection(cadenaConexion)) { string instruccion = " Insert Into Hotel (IdHotel, Nombre, Direccion, Estado, Telefono)" + " Values (@IdHotel, @Nombre, @Direccion, @Estado, @Telefono)"; comando.CommandType = CommandType.Text; comando.CommandText = instruccion; comando.Connection = conexion; comando.Parameters.AddWithValue("@IdHotel", NuevoHotel.IDHotel); comando.Parameters.AddWithValue("@Nombre", NuevoHotel.NombreHotel); comando.Parameters.AddWithValue("@Direccion", NuevoHotel.DireccionHotel); comando.Parameters.AddWithValue("@Estado", NuevoHotel.StatusHotel); comando.Parameters.AddWithValue("@Telefono", NuevoHotel.TelefonoHotel); conexion.Open(); Debug.WriteLine("Aqui voy bien 7"); hotelregistrado = comando.ExecuteNonQuery() > 0; } } catch (InvalidOperationException) { Debug.WriteLine("No puedo escribir en la base de datos"); } return hotelregistrado; } } }
异常情况
运行代码输入Hotel对象数据时,执行到conexion.Open()前一切正常,但此时抛出异常:
'System.InvalidOperationException' in Microsoft.Data.SqlClient.dll
已检查连接字符串未发现问题,数据库文件与C#解决方案不在同一目录(在上一级目录),不确定是否因使用Microsoft.Data.SqlClient导致该问题。
排查与解决方案
捕获完整异常信息
当前catch块仅输出固定文本,无法定位具体问题。修改代码输出完整异常细节,包括消息和内部异常:catch (InvalidOperationException ex) { Debug.WriteLine($"异常详情: {ex.Message}"); if (ex.InnerException != null) { Debug.WriteLine($"内部异常: {ex.InnerException.Message}"); } } catch (Exception ex) { Debug.WriteLine($"其他异常: {ex.Message}"); }验证SQL Server服务状态
- 打开服务管理器(运行
services.msc),检查**SQL Server (SQLEXPRESS)**服务是否处于运行状态,未启动则手动启动。 - 通过SQL Server Management Studio(SSMS)尝试连接
DESKTOP-QG08OQQ\SQLEXPRESS实例,确认实例名称和数据库Script_RESORTSUNED存在。
- 打开服务管理器(运行
检查Windows身份验证权限
当前连接字符串使用Integrated Security=True,即Windows账户登录。确认运行程序的Windows账户拥有Script_RESORTSUNED数据库的写入权限(至少分配db_datawriter角色),权限不足则在SSMS中为账户添加对应权限。Microsoft.Data.SqlClient兼容性检查
- 确认项目中
Microsoft.Data.SqlClient包版本与SQL Server版本兼容,优先安装稳定版(如v5.x系列)。 - 若怀疑包的问题,可临时切换到旧版
System.Data.SqlClient测试,看异常是否消失。
- 确认项目中
数据库文件权限与路径验证
若数据库是附加的mdf/ldf文件:- 在SSMS中查看数据库的物理文件路径,确认路径正确且文件存在。
- 确保运行程序的账户拥有该文件的读写权限。
内容的提问来源于stack exchange,提问作者Kabir
相关产品推荐
相关产品推荐

