参数化查询需要未提供的参数 p1

The parameterized query expects the parameter p1 which was not supplied

我有一个存储过程如下:

CREATE PROCEDURE [dbo].[MyProc] 
    @p1 as int,
    @p2 as smalldatetime,
    @p3 as int,
    @p4 as varchar(255),
    @p5 as int = null,
    @p6 as numeric(18,2) = 0,
    @p7 as char(2) = null
AS

...

当我执行下面的命令时,我得到了结果:

EXEC dbo.MyProc
    @p1 = 0,
    @p2 = '5/29/2015',
    @p3 = NULL,
    @p4 = NULL,
    @p5 = 233,
    @p6 = 0,
    @p7 = NULL

但是当我使用 Entity Framework 的 Database.SqlQuery 时,我得到 The parameterized query '(@p1 bigint @p2 datetime @p3 nvarchar(4' expects the parameter '@p1' which was not supplied. 下面是我使用的代码。

using (var context = new DbContext())
{   
    context.Database.ExecuteSqlCommand(
        @"EXEC dbo.MyProc @p1, @p2, @p3, @p4, @p5, @p6, @p7",
        new SqlParameter("p1", 0),
        new SqlParameter("p2", myDate), //myDate has value
        new SqlParameter("p3", DBNull.Value),
        new SqlParameter("p4", DBNull.Value),
        new SqlParameter("p5", myValue),//myValue has value
        new SqlParameter("p6", 0),
        new SqlParameter("p7", string.Empty));//I tried this with DBNull.Value; but no difference
}

有人能帮忙吗?

”不知为什么,我传0的时候,它被转换成了BigInt。我不知道为什么。 我将 0 解析为 int 并且它起作用了。

using (var context = new DbContext())
{   
    context.Database.ExecuteSqlCommand(
        @"EXEC dbo.MyProc @p1, @p2, @p3, @p4, @p5, @p6, @p7",
        new SqlParameter("p1", int.Parse("0"),
        new SqlParameter("p2", myDate),
        new SqlParameter("p3", DBNull.Value),
        new SqlParameter("p4", DBNull.Value),
        new SqlParameter("p5", myValue),
        new SqlParameter("p6", int.Parse("0")),
        new SqlParameter("p7", DBNull.Value));
}

在声明 SqlParameter 时,“@”是可选的,有或没有都可以。使用 SqlParameter 重载 (string, object) 时,您可以像这样转换一个常量值,例如 0:

new SqlParameter("@p1", (object)0)

因为它确实需要一个对象。这也适用于较新的 Microsoft.Data.SqlClient 程序集。