Handle DBNull in C#

前端 未结 13 750
梦谈多话
梦谈多话 2020-11-30 01:36

Is there a better/cleaner way to do this?

int stockvalue = 0;
if (!Convert.IsDBNull(reader[\"StockValue\"]))
    stockvalue = (int)reader[\"StockValue\"];
         


        
13条回答
  •  -上瘾入骨i
    2020-11-30 02:15

    int? stockvalue = (int?)(!Convert.IsDBNull(result) ? result : null);
    

    One possible solution so that you ensure that the DBNull carries across to your code. For our group, as a best practice, we try and not allow NULL columns in the database unless its really needed. There is more overhead in coding to handle it, and sometimes just rethinking the problem makes it so its not required.

提交回复
热议问题