Can someone explain why this exception is occuring the in the following LINQ query:
return (from c in dc.Classifications
where c.Id == classificationId
select new Classification()
{
Description = c.Description,
ParentId = Convert.ToInt16(c.ParentId),
}).Single<Classification>();
dc is the datacontext, Classification is a class containing the int property ParentId. The ParentId column is a nullable int from a Sql Server database. In the case of the ParentId field being null in the database, the statement returns an InvalidOperationException.
In other words, why does the above query fail and
'int y = Convert.ToInt16(null);'
work?
Best Answer
Assuming that you want to have 0 as
ParentId
when it is NULL in the database:My answer also assumes, that
Classifications.ParentId
is of typeNullable<int>
/int?
and its value isnull
if the column is NULL in the database.The only thing I changed, was the
?? 0
part in the convert. It uses0
in casec.ParentId
isnull
andc.ParentId
otherwise. See ?? Operator for more info.