【问题标题】:Unable to cast DBNull to string无法将 DBNull 转换为字符串
【发布时间】:2013-03-24 20:37:17
【问题描述】:

在我使用 Signalr 的 ASP.NET WEB API 应用程序中,我使用以下代码

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

                        }).ToList();

当我在数据库中有 CustomerName 和 CustomerAddress 时,这可以正常工作。但是当我有任何一列NULL时它失败了。我遇到了运行时错误

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

我该如何处理?

【问题讨论】:

    标签: .net datareader


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2014-03-15
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2019-07-23
      相关资源
      最近更新 更多