开发者

Handling DBNull and null in ASP.NET

开发者 https://www.devze.com 2023-04-03 19:37 出处:网络
What is the best way of rewriting these (erroneous) lines? bool? result = dr[\"result\"] == DBNull.Value ? null : Convert.ToInt32(dr[\"result\"]);

What is the best way of rewriting these (erroneous) lines?

bool? result = dr["result"] == DBNull.Value ? null : Convert.ToInt32(dr["result"]);

...and...

dr["result"] = result ?? DBNull.Value;

Both do not compile.

I am using the MySql connector and it doesn't let me set, for example, dr["result"] = null; which is what I first tried.

Is there an mor开发者_C百科e suitable .NET data type for representing a MySql nullable tinyint(1)?


How about:

     dr["Hello"] = (object)result ?? DBNull.Value;
     bool? result = dr["result"] == DBNull.Value ? null : (bool?)(Convert.ToInt32(dr["result"]) != 0);

The reason your suggestion does not compile is that both alternatives of the ternary operator ?: must have the same type. DBNull.Value obviously is not the same type as a bool?. Casting the bool? to an object however makes them both the same type. Similar rules apply on the second row.


If you are using a stored procedure or SQL queries then you can use ISNULL() function of SQL to handle NULL...

0

精彩评论

暂无评论...
验证码 换一张
取 消