C# System.Linq.Dynamic: How to pass in the object [] params to SqlQuery
Why does:
IEnumerable<MyEntity> MyFunction(string sql, object [] params)
{
// EG:
// "SELECT * FROM MyTable WHERE MyField0 = @0 AND MyField1 = @1"
// params = { 1, "UK" }
return Context.Database.SqlQuery<TEntity>(sql, params);
}
...give me the following error?:
Must declare the开发者_开发百科 scalar varliable "@0"
I know it would work if I did:
var query = Context.Database.SqlQuery<TEntity>(
"SELECT * FROM MyTable WHERE MyField0 = @0 AND MyField1 = @1", 1, "UK"
);
... but I want to abstract the code and call it as, for example:
var x = MyFunction(
"SELECT * FROM MyTable WHERE MyField0 = @0 AND MyField1 = @1", 1, "UK"
);
Ie, my problem is that I can't figure out how to pass in an array of params.
EDIT:
The accepted answer answers the question, but there is another problem in there: you need to parametrize the array, ie, instead of just the values, pass them as an array of named SqlParameters. See:
SqlQuery and parameters
You need to include the params
keyword to the "parameters" parameter:
IEnumerable<MyEntity> MyFunction(string sql, params object[] parameters)
{
return Context.Database.SqlQuery<TEntity>(sql, parameters);
}
精彩评论