Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle a NULLable Int column returned from a stored procedure in LINQ to SQL

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.

like image 816
Collin Estes Avatar asked Jan 05 '09 19:01

Collin Estes


People also ask

Can we use stored procedure in Linq?

Language-Integrated Query (LINQ) makes it easy to access database information, including database objects such as stored procedures. The following example shows how to create an application that calls a stored procedure in a SQL Server database.

How do you handle NULL values in SQL?

Handling SQL NULL values with Functions ISNULL(): The ISNULL() function takes two parameters and it enables us to replace NULL values with a specified value. The expression parameter indicates the expression which we want to check NULL values.

How do you handle database NULL values in C #?

Use of NULL Values in C#Any type is known as nullable if you can assign a value or null to this variable it means that the type will have no value. In C# all reference types like string are of a nullable type, but the other types like int32 are not nullable type.

Can stored procedure return NULL value?

Try to return a NULL value in a stored procedureIn some cases, a NULL value ​​can be assigned to the stored procedure return value when changing it. At this point, SQL Server automatically converts NULL values into 0. The example below describes a scenario similar to this.


2 Answers

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?

like image 61
Micah Avatar answered Nov 03 '22 01:11

Micah


Try declaring the int variables as nullable. I.e.

int? myInt;

This way you can check them for null.

like image 34
Perry Neal Avatar answered Nov 03 '22 00:11

Perry Neal