C# – How to handle a NULLable Int column returned from a stored procedure in LINQ to SQL

asp.netclinq-to-sqlstored-procedures

I have a stored procedure that returns two int Values. The first can not be null but the second can actually return a null value. When I try to execute my stored procedure using LINQ to SQL it fails with the statement:

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

I tried to change my designer file in my DBML and add in: CanBeNull= true to the Column mapping of the Stored Procedures Result.

I'm can seem to figure out the correct way to handle this, not sure if I can change my LINQ/C# code to account for the null (which would be preferable) or if I will have to update my Stored Procedure in some fashion.

Best Answer

You need to declare the variable to be nullable. In the designer, click the property in your model that needs to be nullable, and then in the Properties window, set the "Nullable" property to True. This will tell the generator to create your property as Nullable<int> or int?