有人能解释为什么这个异常在下面的LINQ查询存在的了:例外:空值不能分配与类型System.Int32一个成员是一个非空的值类型
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中使用什么值? – Kipotlov 2011-03-28 15:12:05
int x = Convert.ToInt16(matches.Single()。ParentId);当这个ParentId在db中为空时,这不会抛出任何异常吗?......奇怪! – 2011-03-28 15:21:04
如果数据库字段为空,我希望ParentId为零。 – Will 2011-03-28 19:15:33