An exception of type 'System.NullReferenceException' occurred in EntityFramework.dll but was not handled in user code : Executing a stored procedure

c# entity-framework

Question

I have my code below:

 User user = new User();
  WFMModel db = new WFMModel();
  SqlParameter param1 = new SqlParameter("@username", username);
  SqlParameter param2 = new SqlParameter("@password", password);
  SqlParameter param3 = new SqlParameter("@Version", Version);`



var userData = db.Database.SqlQuery<User>("usp_Rep_App_DotNet_Validate_User_new @username,@password,@Version",
param1, param2, param3);

And I have my User class as below:

public class User
    {
        public string UserID;
        public string FirstName;
        public string LastName;
        public string Message;
        public string Department;
    }

But when the code executes, I get the error: An exception of type 'System.NullReferenceException' occurred in EntityFramework.dll but was not handled in user code.

When I run the stored procedure, I get the data without any issues (no nulls as well).

Any idea what's going on? Thanks in advance.

1
0
1/9/2017 9:05:38 PM

Accepted Answer

One of the variables that you are passing into your parameters (either username, password, or Version) is likely null. Set a breakpoint, and then hover your mouse over each variable to see which one is throwing the exception. You need to take appropriate measures to check these values for null before using them in your query.

If you wish for the parameter to be "null" from SQL Server's perspective, you would need to use DBNull.Value - databases use DBNull, C# uses null, and they are not interchangeable (although you might expect that they would be.)

1
1/9/2017 9:08:28 PM

Popular Answer

I myself ran into a lot of troubles when trying to retreive the return of a SQL stored proc with Entity, theres is about 3 way to do so correctly, here's the links :

This methode worked for me :

Sql Stored proc and Entity framework 6

Many people rather like :

using stored procedure in entity framework

And here is the long but normal way, that most people use :

Getting data from stored procedure with Entity Framework

Surely you will be able to use one of these 3 ways has they all do the same thing : retreive the return of the stored proc.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow