开发者

In Ado.Net, can I determine if columns in result sets are nullable?

开发者 https://www.devze.com 2023-04-04 02:40 出处:网络
I need to determine the structure of a result set returned by ExecuteReader. I am using the following approach:

I need to determine the structure of a result set returned by ExecuteReader. I am using the following approach:

    public List<NameAndType> ResultSetStructure(DataTable columns)
    {
        var ret = new List<NameAndType>();
        foreach (DataRow column in columns.Rows)
        {
            ret.Add(new NameAndType { Name = column[NameIndex].ToString(),
                                          Type = column[TypeIndex].ToString()
            });
        }
        return ret;
    }

(snip)

 using (SqlDataReader dr = command.ExecuteReader())
        {

            var rawColumns = dr.GetSchemaTable();
            var columns = ResultSetStructure(rawColumns);

This gives me column names and types, but I would also like to know if the column is nullable, so that I know which of the following options to choose:

decimal density = dr.GetDecimal(0); 
decimal? density = dr.IsDBNull(0) ? (decimal?)null : dr.GetDecimal(0); 

Can I accomplish that? TIA.

Edit: I just found what I need:

开发者_JS百科
column[13].ToString()


I guess there is no such way to know whether a column is nullable or not. You can try writing an extension method something like below:

     public static decimal GetDecimal(this SqlDataReader reader, int columnIndex) 
     {    
        if(!reader.IsDBNull(columnIndex))  
             {      
             return reader.GetDecimal(colIndex);    
          }
         else
           {
                   return 0; 
         }
       }

Hope this would be some help!!


The following code gets the job done:

            ret.Add(new NameAndType { Name = column[NameIndex].ToString(),
                                          Type = column[TypeIndex].ToString(),
                                          IsNullable = column[13].ToString().Equals("True")
0

精彩评论

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

关注公众号