在我使用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'.
我该如何处理?
答案 0 :(得分: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();