Tuesday, January 21, 2014

The parameterized query ... expects the parameter ..., which was not supplied

After spending too much time on a null parameter issue, I finally found the solution!  If you try to execute a parameterized query against an object context in Entity Framework it's not enough to create a parameter and set it null.  You'll get the dreaded "was not supplied" error.  Instead, you have to explicitly set the value to DbNull.Value.

Bad Example:
string x = null;
var p1 = new SqlParameter("param1", x);

Good Example:
string x = null;
var p1 = new SqlParameter("param1", x);
if( x == null ) p1.Value = DbNull.Value;

The more you know!