简体   繁体   中英

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

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.

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.)

Are you sure that your UserID column will return string and not an integer?

Also probably one of your parameter values is null.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM