我有一个自定义编写的数据库提供程序。当我运行我的测试时,他们会使用ExecuteScalar
打破NullReferenceException
命令。我可能会在这里失踪什么?我读过一些人有一个MultiThreading问题,但我并没有“认为”这就是我遇到的问题。
这是我的GetOpenConnection方法
public SqliteConnection GetOpenConnection()
{
var connection = new SqliteConnection(_connectionString);
if (connection == null) throw new Exception("Could not create a database connection.");
connection.Open();
return connection;
}
和ExecuteScalar方法
public TKey ExecuteScalar<TKey> ( string commandText, IDictionary<string, object> parameters )
{
using ( var connection = _connectionProvider.GetOpenConnection() )
{
using ( var command = connection.CreateCommand() )
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
foreach ( var parameter in parameters )
{
command.Parameters.Add( new SqliteParameter( parameter.Key, parameter.Value ?? DBNull.Value ) );
}
// BREAKING HERE
return ( TKey )command.ExecuteScalar();
}
}
}
这是调用ExecuteScalar
private const string CheckTableExists = "SELECT name FROM sqlite_master WHERE type='table' AND name='{0}'";
public bool CheckIfTableExists ( string tableName )
{
var exists = ExecuteScalar<int>( string.Format( CheckTableExists, tableName ) ) == 1;
return exists;
}
我在其上设置了一个断点,并尝试进入它... ..代码只是中断并抛出异常......我无法追踪它
答案 0 :(得分:8)
ExecuteScalar
返回null。这似乎解决了NullReferenceException。
public TKey ExecuteScalar<TKey> ( string commandText, IDictionary<string, object> parameters )
{
using ( var connection = _connectionProvider.GetOpenConnection() )
{
using ( var command = connection.CreateCommand() )
{
command.CommandType = CommandType.Text;
command.CommandText = commandText;
foreach ( var parameter in parameters )
{
command.Parameters.Add( new SqliteParameter( parameter.Key, parameter.Value ?? DBNull.Value ) );
}
if (typeof (TKey) != typeof (int))
{
return (TKey) command.ExecuteScalar();
}
var executeScalar = command.ExecuteScalar();
var item = executeScalar == null ? 0 : 1;
return (TKey)(object)item;
}
}
}