Linq 和 DBNull - 出现错误
从 rows.AsEnumerable() 中进行选择时出现错误。我正在使用以下代码...
var rows = ds.Tables[0].AsEnumerable();
trafficData = rows.Select(row => new tdDataDC
{
CalculationCount = row.Field<Int64>("biCalculationCountSeqID")
, Zone = row.Field<Int16>("siFkZoneId")
, Miles = row.Field<decimal>("dcMiles")
, Plaza = row.Field<Int16>("siFkPlazaId")
, VehicleCount = row.Field<int>("iVehicleCount")
});
大多数情况下它运行良好,但是当数据库中存在 NULL 时,我收到此错误“无法将 DBNull.Value 转换为类型“System.Int16”。请使用可空类型..” 我该如何纠正这个问题?我不希望我的数据契约具有可为 Null 的类型,我想使用三元或其他类型,如果值为 NULL,则只需使用 0。这可能吗?
感谢您的帮助,
〜ck
I'm getting an error when selecting from a rows.AsEnumerable(). I am using the following code...
var rows = ds.Tables[0].AsEnumerable();
trafficData = rows.Select(row => new tdDataDC
{
CalculationCount = row.Field<Int64>("biCalculationCountSeqID")
, Zone = row.Field<Int16>("siFkZoneId")
, Miles = row.Field<decimal>("dcMiles")
, Plaza = row.Field<Int16>("siFkPlazaId")
, VehicleCount = row.Field<int>("iVehicleCount")
});
Most of the time it works well, but when there are NULLS in the database I'm getting this error "Cannot cast DBNull.Value to type 'System.Int16'. Please use a nullable type.."
How can I correct this? I don't want my datacontracts to have Nullable types, I'd like to use a ternary or something, and if a value is NULL, just use 0. Is this possible?
Thanks for any help,
~ck
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您始终可以添加另一个扩展方法(未经测试):
然后您的调用站点如下所示:
You could always add another extension method (untested):
Then your callsite looks like:
这是测试空值的方法...
Here is how you test for nulls...
如果你的财产可以为空,你也可以这样做;
If your property is nullable you can do this as well;
我非常喜欢
??
运算符:I'm pretty fond of the
??
operator: