I have lots of fields that I need to transfer to a SQL server database table which I’m getting a few problems with NULL values.
I can get around it using something similar to
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd_insert = new SqlCommand("INSERT INTO AccStats (Field1 , Field2 ,
Field3) VALUES (@value1 , @value2 , @value3)", conn);
if (record.commRate == null)
{
cmd_insert.Parameters.AddWithValue("@value1", DBNull.Value);
}
else
{
cmd_insert.Parameters.AddWithValue("@value1", record.commRate);
}
//Lots more fields
conn.Open();
cmd_insert.ExecuteNonQuery();
conn.Close();
}
I just wanted to know if there was a neater/shorter way of doing this rather than writing out this 100’s of times for all the fields?
if (record.commRate == null)
{
cmd_insert.Parameters.AddWithValue("@value1", DBNull.Value);
}
else
{
cmd_insert.Parameters.AddWithValue("@value1", record.commRate);
}
Sure; that is actually a perfect fit for dapper
Basically, dapper treats the (single) parameter object as a key-value store – because
@commRateis in the command, it addsrecord.commRate, using the using rules includingnullvsDBNull(and likewise forrecord.anotherFieldandrecord.yetAnotherField).