ObjectContext.ExecuteStoreCommand无法识别参数

Kev*_*Kev 2 c# sql-server entity-framework

我在这做错了什么?

...
using (var ctx = ObjectContextManager<MyDataContext>.GetManager("MyDataContext"))
{
    var idsToUpdate = "2,3";

    var parameters = new[]
    {
         new SqlParameter("DesiredEndDate", SqlDbType.DateTime).Value = newUpperLimit,
         new SqlParameter("TasksToUpdate", SqlDbType.NVarChar).Value = idsToUpdate
    };

    ctx.ObjectContext.ExecuteStoreCommand("UPDATE dbo.Tasks SET DesiredEndDate = @DesiredEndDate WHERE Id IN (SELECT Id FROM dbo.fn_Split(@TasksToUpdate, N','))", parameters);

    ctx.ObjectContext.SaveChanges();
}
...
Run Code Online (Sandbox Code Playgroud)

我收到了错误

必须声明标量变量"@DesiredEndDate".

必须声明标量变量"@TasksToUpdate".

但我看不出我的代码有什么问题:/

Kev*_*Kev 5

我仍然不明白为什么@ParamName语法不起作用.但是有一个替代方案,它确实有效:

 ctx.ObjectContext
    .ExecuteStoreCommand(
          "UPDATE dbo.Tasks SET DesiredEndDate = {0} WHERE Id IN (SELECT Id FROM dbo.fn_Split({1}, N','))",
          newUpperLimit, 
          idsToUpdate);
Run Code Online (Sandbox Code Playgroud)

这有额外的好处,我不需要创建SqlParameters.

  • 这里没有SQL注入.在内部,ExecuteStoreCommand使用DbCommand.CreateParameter传递参数.请参阅http://stackoverflow.com/questions/5474264/how-to-pass-parameters-to-the-dbcontext-database-executesqlcommand-method中的Josh Gallagher的评论. (2认同)