Search code examples
c#.netdapperxunit

insert null value as interpolated parameter in query


I am trying to build a simple test with xUnit by using InlineData:

[Theory]
[InlineData(null, "Message")]
public void MyTest(object value, string message)
{
    var insertQuery = $@"INSERT INTO {_MyTable} (
                            [MyId]
                        ) VALUES (
                            {value}
                        );";

    using (IDbConnection connection = new SqlConnection(_connectionString))
    {
        connection.Execute(query);
    }
}

I really want to insert the value NULL but when executing it complains:

'Incorrect syntax near ')'.'

And indeed if I go check the query it looks like this:

INSERT INTO TestTable (
        [MyId]
    ) VALUES (
        
    );

so there interpolated parameter is not inserted correctly in the query. How can I do that? Thank you!


Solution

  • Since you've tagged this , basically: don't use interpolated strings; that's not how it is meant to work. Instead:

    using var connection = new SqlConnection(_connectionString);
    connection.Execute(@"
    INSERT INTO TableNameThisShouldBeAConstant ([MyId])
    VALUES (@value);", new { value });
    

    Note that value here would ideally be well-typed as a string/int/etc.