I am trying to use Dapper and Dapper.Contrib to insert a whole object into a table in the databse, while ignoring (because the table has a default value for that column) the properties that have a value set to null.
This is the class of the object I want to insert:
[Table("table_in_database")]
public class Example
{
public int ex_id { get; set; }
public string? ex_desc { get; set; }
}
Assume that the column names in the table (called "table_in_database") match the names of the properties (so there is a column called ex_id and ex_desc). Also assume that ex_desc is nullable and has default value set to "test" in the database.
Now, assume that I create an object of class Example like so:
Example example = new Example()
{
ex_id = 1
};
And then do the following to insert it into the database:
using (DbConnection conn = GetConnection())
{
conn.Insert(example);
//the Insert method comes from Dapper.Contrib.Extensions
}
My problem is that this code inserts NULL in the ex_desc column instead of "test".
The only other post I found that was similar to mine is this, but I don't want to do what is proposed in the accepted answer. I want the database to handle default values (so option 1 and 2 are out), and I don't want to always ignore the ex_desc property since I want the data in the property to be inserted if it's not set to NULL (so option 3 is out).
How could I go about doing this?