What is the best way to deal with DBNull's

后端 未结 14 1035
迷失自我
迷失自我 2020-12-02 15:45

I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this:



        
14条回答
  •  悲哀的现实
    2020-12-02 16:13

    It is worth mentioning, that DBNull.Value.ToString() equals String.Empty

    You can use this to your advantage:

    DataRow row = ds.Tables[0].Rows[0];
    string value = row["name"].ToString();
    

    However, that only works for Strings, for everything else I would use the linq way or a extension method. For myself, I have written a little extension method that checks for DBNull and even does the casting via Convert.ChangeType(...)

    int value = row.GetValueOrDefault("count");
    int value = row.GetValueOrDefault("count", 15);
    

提交回复
热议问题