简体   繁体   English

C#System.Linq.Dynamic:如何将对象[]参数传递给SqlQuery

[英]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. 接受的答案回答了这个问题,但是那里还有另一个问题:您需要对数组进行参数化,即,不只是值,还应将它们作为名为SqlParameters的数组传递。 See: 看到:

SqlQuery and parameters SqlQuery和参数

You need to include the params keyword to the "parameters" parameter: 您需要在“ parameters”参数中包含params关键字:

IEnumerable<MyEntity> MyFunction(string sql, params object[] parameters)
{
    return Context.Database.SqlQuery<TEntity>(sql, parameters);   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM