Last Updated: February 25, 2016
· neelamsk
262292 425479734154770 939732499 n

SqlParameter Constructor Beware...


I was using entity framework to call a stored procedure from code.

SqlParameter param1 = new    SqlParameter("@onlinestatus", true);

SqlParameter param2 = new SqlParameter("@userid", 21425);

SqlParameter param3 = new SqlParameter("@onlineid", 0);

db.Database.SqlQuery<online_stats>("online_stats @onlinestatus, @userid, @onlineid", param1, param2, param3);

But kept getting below error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The parameterized query '(@onlinestatus bit,@userid int,@onlineid int)online_stats @onlin' expects the parameter '@onlineid', which was not supplied.


SqlParameter has some 7 constructors.
Two of which were creating problem for me.

1. SqlParameter(string parametername, Object value)

2. SqlParameter(string parametername, SqlDbType dbtype)

While I intended to use 1st constructor specifying the name & value for my parameter, the value '0' of the parameter was rather being treated as value of SqlDbType (as it is an enum). & i kept getting the above error.

I didn't had any issues with first two parameters as they has following values

@onlinestatus = true & @userid = 21425(which is biig number.)

I would have got the same issue for @userid, if the value was less then 25.


The above error itself is a bit confusing. Anyways, The solution to it was either to use a different constructor or specify the value for the parameter separately.

param3.Value = 0;
Say Thanks