-
Notifications
You must be signed in to change notification settings - Fork 1
Constructing DbParameters from objects
One ore more parameter objects can be passed into the AsSql
method (or SqlString
constructor). These will be used to construct instances of the provider-specific parameter class, which will be added command's Parameters
collection. The parameter object can be a collection of any of the following:
- Provider-specific
DbParameter
-derived class KeyValuePair<string, T>
Tuple<string, T ...>
ValueTuple<string, T ...>
In addition, if the provider supports named parameters, the parameter object can be a an object of a named or anonymous type; the public properties/fields and their values will be used as parameter names and values.
var parameterObject = new Person {
LastName = "Smith",
FirstName = "John"
};
int countOfSmith = "SELECT COUNT(*) FROM Persons WHERE LastName = @LastName AND FirstName = @FirstName"
.AsSql(parameterObject)
.ToList<Person>();
If the provider supports positional parameters, the collection can also contain primitive values -- string
, DateTime
, numeric types. In any event, the parameter names will be ignored.
"INSERT INTO Persons (FirstName, LastName) VALUES (?, ?)".AsSql(
new [] {"John", "Smith"}
).Execute();
(Note that if the provider only supports positional parameters, passing in a plain object is not a good idea, since there is no guarentee of the order in which the properties will be returned, and thus no control over which parameter has whcih value.)
For information about whether a given provider supports named or positional parameters, see here.