简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM