【发布时间】:2014-01-17 14:14:46
【问题描述】:
有人可以解释为什么在以下 LINQ 查询中会发生此异常:
return (from c in dc.Classifications
where c.Id == classificationId
select new Classification()
{
Description = c.Description,
ParentId = Convert.ToInt16(c.ParentId),
}).Single<Classification>();
dc 是datacontext,Classification 是一个包含int 属性ParentId 的类。 ParentId 列是来自 Sql Server 数据库的可为空的 int。在数据库中 ParentId 字段为空的情况下,该语句将返回 InvalidOperationException。
也就是说,上面的查询为什么会失败?
'int y = Convert.ToInt16(null);'
工作吗?
【问题讨论】:
-
当数据库中的字段为空时,您希望 ParentID 中的值是多少?
-
int x = Convert.ToInt16(matches.Single().ParentId);当数据库中的 ParentId 为 null 时,这不会引发任何异常吗?...奇怪!!!
-
如果数据库字段为空,我希望 ParentId 为零。
-
我的解决方案对您没有帮助吗?还请发布该
InvalidOperationException的确切错误消息和堆栈跟踪。 -
@Daniel Hilgarth:是的,我已经更改了代码以使用 c.ParentId ? 0. 但是,我也想知道为什么转换在 Linq2Sql 中不起作用。抱歉不清楚。
标签: c# linq linq-to-sql