I noticed that when Entity Framework generates a method for a stored procedure (function import), it tests to see if the parameter is null, and makes a decision like this:
if (contactID.HasValue)
{
contactIDParameter = new ObjectParameter("contactID", contactID);
}
else
{
contactIDParameter = new ObjectParameter("contactID", typeof(global::System.Int32));
}
I don’t understand what its trying to do by passing the Type of the parameter as a parameter when the parameter is null? Exactly how does the stored procedure/function get executed in this case?
I did a test myself with SQL Profiler, and noticed that when I intentionally pass null as a parameter (by calling something like context.MyProcedure(null) ), null is simply passed as the parameter to the SQL server’s stored procedure.
Some clarifications on this behavior would be appreciated.
I was interested in this question so I made some investigation.
ObjectParameterhas two overloads – one for passing value and one for passing the type. The second is used if you pass null as the parameter value because EF internally need this. The reason is that function import must be called with ObjectParameters, not with plain parameters you are passing to the wrapping method.Internally EF calls:
As you can see even null value must be represented as ObjectParameter because you can’t simply pass null – it will throw exception. The
PopulateFunctionEntityCommandParametersuses information about the type to create correctDbParameterfor calling the stored procedure. The value of that parameter isDBNull.Value.So you don’t have to deal with it. It is just infrastructure.