I am not directly familiar with any tool with a SingleDecimal
method, so I'll answer in the general sense:
When querying data from ADO.NET (directly or indirectly), it is pretty likely that (possibly both) you will get some kind of "reader" API (most likely IDataReader
), or that you will get raw object
values.
In the first case, you should have access to an IsDBNull
method (per column); so call that method, and do whatever you want to do with nulls.
In the second case, you should check the value for DBNull
, i.e. if(val is DBNull
).
In both cases, what the code does next is up to the library. In both cases, you might need to think about two null-esque scenarios here: no rows, and a row with a single value.
Frankly, in both cases it would be easier to use a library/tool that has existing support for this. For example, with dapper, this would just be:
string customerId = "01";
decimal? pembayaran = Db.Query<decimal?>(
"Select valuta from ArInvoice where customerID=@customerId",
new { customerId }).Single();
which gives you:
- correct parameterisation
- null handling
- the same API for querying all data (
Query<T>
)
- the ability to use any LINQ you like for ordinality (
Single()
, First()
, ToList()
, etc)
If you wanted to use a default value (rather than an empty decimal?
when the cell's value was null
, you could just use:
decimal pembayaran = Db.Query<decimal?>(
"Select valuta from ArInvoice where customerID=@customerId",
new { customerId }).Single() ?? 0M;
here note the ?? 0M
is just a null-coalescing operation to get a zero decimal
in place of null
.