使用SqlCommand和迷你分析器时,连接未初始化
本文关键字:连接 初始化 分析器 SqlCommand 使用 | 更新日期: 2023-09-27 18:11:27
我收到错误"连接属性尚未初始化"与以下代码:
DbConnection connection = new SqlConnection(connStr);
connection.Open();
connection = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current);
SqlCommand command = new SqlCommand("GetLanguages", connection as SqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 240;
command.ExecuteReader();
当它到达command.ExecuteReader();线。
如果删除
connection = new StackExchange.Profiling.Data.ProfiledDbConnection(connection, MiniProfiler.Current);
则代码工作正常。是什么原因导致我的执行读取器抛出错误?
是什么原因导致我的执行读取器抛出错误?
在创建了ProfiledDbConnection
之后,它就不再是SqlConnection
了,是吗?所以这一行:
SqlCommand command = new SqlCommand("GetLanguages", connection as SqlConnection);
是有效的:
SqlCommand command = new SqlCommand("GetLanguages", null);
…这对执行查询来说不是好兆头。这就是为什么无条件地使用as
是一个坏主意-如果您使用强制转换表达式,将会抛出一个更有用的异常。
从MiniProfiler文档中我不清楚你是如何使用ProfiledDbConnection
和SqlCommand
的。您很可能想使用ProfiledDbCommand
代替。