Entity Framework Parameter Differences
When using EF there is no constructor on DbParameter that takes arguments, and that makes sense. It is meant to be overridden by the concrete type under it, usually SqlDbParameter. Because of this there is also no method for AddWithValue on the DbParameterCollection, which confuses people on occasion.
I just posted a handy extension method to MSDN forums to help turn this:
1: var p = cmd.CreateParameter();
2: p.ParameterName = "Latitude";
3: p.Value = (double?)this.latitude;
4: cmd.Parameters.Add(p);
Into this:
1: cmd.AddParameterWithValue("Latitude", (double?)this.latitude);
Here is the method:
1: /// <summary>
2: /// Adds a parameter to the command.
3: /// </summary>
4: /// <param name="command">
5: /// The command.
6: /// </param>
7: /// <param name="parameterName">
8: /// Name of the parameter.
9: /// </param>
10: /// <param name="parameterValue">
11: /// The parameter value.
12: /// </param>
13: /// <remarks>
14: /// </remarks>
15: public static void AddParameterWithValue(this DbCommand command, string parameterName, object parameterValue)
16: {
17: var parameter = command.CreateParameter();
18: parameter.ParameterName = parameterName;
19: parameter.Value = parameterValue;
20: command.Parameters.Add(parameter);
21: }
Comments
Post a Comment