How to provide object [] params to SqlQuery in C# System.Linq.Dynamic

c# dynamic-linq

Question

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

1
1
5/23/2017 10:34:29 AM

Accepted Answer

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);   
}
1
9/18/2011 12:06:17 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow