使用SQL Server命名参数与ExecuteStoreQuery和ExecuteStoreCommand [英] Using SQL Server named parameters with ExecuteStoreQuery and ExecuteStoreCommand

查看:361
本文介绍了使用SQL Server命名参数与ExecuteStoreQuery和ExecuteStoreCommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SQL Server命名参数与 ObjectContext.ExecuteStoreQuery ObjectContext.ExecuteStoreCommand 当调用存储程序或函数直接。



SQL Server命名参数与Entity Framework命名参数不同 - 它们允许我执行与此类似的查询: p>

  EXEC sp_GetData @firstParameter = 1,@thirdParameter = 2,@secondParameter = 1 
/ pre>

此查询中的参数顺序并不重要,而不是按照按顺序评估的Entity Framework命名参数。



我想用Entity Framework使用SQL Server命名参数,以便如果在存储过程中更改参数的顺序,则调用它的Entity Framework代码不受影响。

解决方案

为了让您按照您的期望工作,您需要设置查询文本a一个参数化查询。棘手的部分是,您只需要确保您的参数的名称与SP参数不同:

  var cmdText =[ DoStuff] @Name = @name_param,@Age = @age_param; 
var @params = new [] {
new SqlParameter(name_param,Josh),
new SqlParameter(age_param,45)
};

ObjectContext.ExecuteStoreQuery< MyObject>(cmdText,@params);


I am trying to use SQL Server named parameters with ObjectContext.ExecuteStoreQuery and ObjectContext.ExecuteStoreCommand when calling a stored procedure or a function directly.

SQL Server named parameters are not the same with the Entity Framework named parameters - they allow me to execute a query similar with this one:

EXEC sp_GetData @firstParameter = 1, @thirdParameter = 2, @secondParameter = 1

The order of the parameters in this query does not matter as opposed with Entity Framework named parameters that are evaluated in order.

I want to use SQL Server named parameters with Entity Framework so that if the order of the parameters is changed in the stored procedure the Entity Framework code calling it is not affected.

解决方案

In order to get this to work as you would expect, then you need to set up the query text as a parameterized query. The tricky part is that you just need to make sure your parameters are named differently than the SP parameters:

var cmdText = "[DoStuff] @Name = @name_param, @Age = @age_param";
var @params = new[]{
   new SqlParameter("name_param", "Josh"),
   new SqlParameter("age_param", 45)
};

ObjectContext.ExecuteStoreQuery<MyObject>(cmdText, @params);

这篇关于使用SQL Server命名参数与ExecuteStoreQuery和ExecuteStoreCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆