将Database.ExecuteSqlCommand与参数一起使用的正确语法是什么? [英] What is the correct syntax for using Database.ExecuteSqlCommand with parameters?

查看:126
本文介绍了将Database.ExecuteSqlCommand与参数一起使用的正确语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Entity Framework 4.2,并且想要调用具有输入参数的存储过程。我正在使用 Database.ExecuteSqlCommand 调用存储过程。

I use Entity Framework 4.2 and want to call a stored procedure that has input parameters. I'm using Database.ExecuteSqlCommand to call the stored procedure.

但是,文档缺少正确的调用的语法,以便正确映射参数。
我的google-foo让我失败了,我们将不胜感激。

However, the documentation is lacking in the correct syntax for the call in order to map the parameters correctly. My google-foo is failing me, and any help will be appreciated.

即我有一个过程

procedure SetElementFrequency
  @ElementTypeID integer,
  @Frequency float
as ...

我尝试用

Database.ExecuteSqlCommand("exec SetElementFrequency @p0 @p1", 
                            elementType, frequency);

Database.ExecuteSqlCommand("exec SetElementFrequency {0} {1}", 
                            elementType, frequency);

,但是它们都失败,并显示错误'@ p1'附近的语法不正确。

but they both fail with the error Incorrect syntax near '@p1'.

推荐答案

根据您的基础数据库提供程序,可以使用以下任意一种。

Depending on your underlying database provider, you can use either of the following.

Database.ExecuteSqlCommand(
    "exec SetElementFrequency {0}, {1}",
    elementType, frequency); 

Database.ExecuteSqlCommand("exec SetElementFrequency ?, ?", elementType, frequency); 

您还可以指定 elementType frequency as DbParameter 的对象,可通过 ParameterName 属性。

You may also specify elementType and frequency as DbParameter-based objects to provide your own names via the ParameterName property.

这篇关于将Database.ExecuteSqlCommand与参数一起使用的正确语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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