2013-03-24 29 views
1

在我的ASP.NET Web API应用程序,它使用Signalr我使用下面的代码无法施展的DBNull串

using (var reader = command.ExecuteReader()) 
        return reader.Cast<IDataRecord>() 
         .Select(x => new CustomerInfo() 
         { 
          CustomerName = x.GetString(0), 
          CustomerAddress = x.GetString(1), 

         }).ToList(); 

这是工作正常,当我在数据库中有两个客户名称和CustomerAddress。但是当我有任何一列NULL时失败。我正在低于运行时间错误

Unable to cast object of type 'System.DBNull' to type 'System.String'. 

我该如何处理?

回答

1

您可以用as关键字做到这一点:x[0] as string

using (var reader = command.ExecuteReader()) 
    return reader.Cast<IDataRecord>() 
       .Select(x => new CustomerInfo() 
       { 
        CustomerName = x[0] as string, 
        CustomerAddress = x[1] as string,  
       }).ToList(); 
相关问题