C# – Exception: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type

clinqlinq-to-sql

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:

    return (from c in dc.Classifications
            where c.Id == classificationId
            select new Classification()
            {
                Description = c.Description,
                ParentId = Convert.ToInt16(c.ParentId ?? 0),
            }).Single<Classification>();

My answer also assumes, that Classifications.ParentId is of type Nullable<int>/int? and its value is null if the column is NULL in the database.

The only thing I changed, was the ?? 0 part in the convert. It uses 0 in case c.ParentId is null and c.ParentId otherwise. See ?? Operator for more info.