实体框架ExecuteSqlCommand缺少输入参数

时间:2015-03-31 20:10:01

标签: c# sql sql-server entity-framework

我在Entity Framework(EF)中遇到ExecuteSqlCommand()方法的问题。我有以下SQL Server存储过程:

EXEC SomeSchema.SomeTableInsert
@Id = 1, 
@SomeData = 'This is some random data', 
@UserId = 500

它没有任何问题。当我尝试使用EF的ExecuteSqlCommand()方法时,我收到以下错误:

Procedure or function 'SomeTableInsert' expects parameter '@UserId', which was not supplied.

这是C#代码:

var sql = "SomeSchema.SomeTableInsert @Id, @SomeData, @UserId";
var sqlParameters = new List<SqlParameter> 
{ 
    new SqlParameter("@Id", 1),
    new SqlParameter("@SomeData", "This is some random data"), 
    new SqlParameter("@UserId", 500)
};

dbContext.Database.ExecuteSqlCommand(sql, sqlParameters.ToArray<object>());

我不明白为什么我收到这个错误。 UserId参数不会丢失,并且具有有效值。有什么想法吗?

更新

以下是在SQL Server上运行的SQL:

exec sp_executesql 
    N'SomeSchema.SomeTableInsert @Id, @SomeData, @UserId',
    N'@Id int,@SomeData nvarchar(5),@UserId int',
    @Id=1,
    @SomeData='This is some random data',
    @UserId=500

1 个答案:

答案 0 :(得分:1)

var sql = "SomeSchema.SomeTableInsert @Id, @SomeData, @UserId";
var sqlParameters = new List<SqlParameter> 
{ 
    new SqlParameter("Id", 1),
    new SqlParameter("SomeData", "This is some random data"), 
    new SqlParameter("UserId", 500)
};

dbContext.Database.ExecuteSqlCommand(sql, sqlParameters.ToArray<object>());

从SqlParameter中删除@前缀。