What is the best way to deal with DBNull's

后端 未结 14 944
迷失自我
迷失自我 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:18

    If you have control of the query that is returning the results, you can use ISNULL() to return non-null values like this:

    SELECT 
      ISNULL(name,'') AS name
      ,ISNULL(age, 0) AS age
    FROM 
      names
    

    If your situation can tolerate these magic values to substitute for NULL, taking this approach can fix the issue through your entire app without cluttering your code.

    0 讨论(0)
  • 2020-12-02 16:19

    Add a reference to System.Data.DataSetExtensions, that adds Linq support for querying data tables.

    This would be something like:

    string value = (
        from row in ds.Tables[0].Rows
        select row.Field<string>(0) ).FirstOrDefault();
    
    0 讨论(0)
提交回复
热议问题