DBNull is frankly a bit of a PITA - and it bites lots of people. However, one way to avoid this pain is to use an ORM or micro-ORM that will make this problem go away. For example, with dapper:
int id = ...
string odjezd = ...
...
connection.Execte("insert SomeTable (...) values (@id, @odjezd, ...)",
new {id, odjezd, ... });
Here dapper will automatically parameterize the values correctly, inlcuding treating null
-references and empty Nullable<T>
as DBNull.Value
. Plus it means you avoid all the "fun" of ADO.NET, simply having to worry about:
- connection management
- the sql
- what the parameter values are (but not the parameterization itself)
Note that dapper also has great tools in terms of materialization too, to avoid all the pain of data-readers.