Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.InvalidCastException: 'The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects.'

I migrated my project from ASP.NET Core 2.2 to ASP.NET Core 3.0. Now I get this exception. In ASP.NET Core 2.2 it was using FromSql(); now it is using FromSqlRaw(). I am calling my procedure using Entity Framework Core.

SqlParameter Username = new SqlParameter
            {
                ParameterName = "USERNAME",
                SqlDbType = SqlDbType.NVarChar,
                Value = user.Username,
                Direction = ParameterDirection.Input,
                Size = 50
            };

SqlParameter Password = new SqlParameter
            {
                ParameterName = "PASSWORD",
                SqlDbType = SqlDbType.NVarChar,
                Value = user.Password,
                Direction = ParameterDirection.Input,
                Size = 50
            };

SqlParameter msgOut = new SqlParameter
            {
                ParameterName = "MSG",
                SqlDbType = SqlDbType.NVarChar,
                Direction = ParameterDirection.Output,
                Size = 1000
            };

SqlParameter statusOut = new SqlParameter
            {
                ParameterName = "STATUS",
                SqlDbType = SqlDbType.Int,
                Direction = ParameterDirection.Output
            };

var sql = @"EXEC PRC_USERS_LOGIN
                        @USERNAME, 
                        @PASSWORD, 
                        @MSG OUT, 
                        @STATUS OUT";

Users resultUser = new Users();
resultUser = ctx.Users.FromSqlRaw(sql, Username, Password, msgOut, statusOut)
                      .FirstOrDefault();
like image 669
Muhammad Aftab Avatar asked Sep 29 '19 07:09

Muhammad Aftab


2 Answers

This code worked after replacing

System.Data.SqlClient.SqlParameter

to

Microsoft.Data.SqlClient.SqlParameter

and

FirstOrDefault();

to

ToList();
like image 92
Muhammad Aftab Avatar answered Sep 16 '22 14:09

Muhammad Aftab


Fixed by changing using System.Data.SqlClient to using Microsoft.Data.SqlClient

https://github.com/aspnet/EntityFrameworkCore/issues/16812#issuecomment-516013245

like image 41
LRFalk01 Avatar answered Sep 18 '22 14:09

LRFalk01