Sqlite ExecuteScalar throws NullReferenceExcpetion

I have a custom database provider. When I run my tests, they break into a command ExecuteScalarwith NullReferenceException. What am I missing here? I read that some people have a problem with MultiThreading, but I do not “think” that I am confused.

Here is my GetOpenConnection method

public SqliteConnection GetOpenConnection()
{
    var connection = new SqliteConnection(_connectionString);
    if (connection == null) throw new Exception("Could not create a database connection.");

    connection.Open();

    return connection;
}

And the ExecuteScalar method

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();
        }
    }
}

And this is the method calling 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;
}

I set a breakpoint on it and try to enter it ... and the code just breaks and throws an exception ... I can not track it

+4
source share
1 answer

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;

        }
    }
}
+7

All Articles