【发布时间】:2019-06-08 15:20:47
【问题描述】:
这个问题得到了很好的回答,但我无法正确回答。我正在尝试使用带有一些参数的实体框架从 .NET Core 项目调用存储过程。其中一个参数应该是数组(我通过创建自定义表数据类型来考虑 SQL Server 中的表类型)类型。我关注了this Stackoverflow link。但是当我尝试执行我的 SQL 命令时出现错误。
这是我的代码:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
foreach (var section in model.VMSectionIds) //model.VMSectionIds contains set of integers
{
dt.Rows.Add(section);
}
最后我这样调用存储过程:
var sectiolist = new SqlParameter("@Sections", SqlDbType.Structured)
{
TypeName = "[dbo].[SectionList]",
Value = dt
};
_db.ExecuteSqlCommand("EXEC [SP_GenerateRegularEmployeeSalary] "+mastermodel.ID+","+ fromdate + "," + todate + ",1," + sectiolist + ""); //don't worry I took care of SQL injection for others parameter
但是这个执行抛出异常
SqlException:必须声明标量变量“@Sections”
我无法弄清楚确切的问题出在哪里。这里从 SQL 调用存储过程(带有一些静态测试参数),以便清楚地了解我的存储过程调用机制:
DECLARE @data [SectionList]
INSERT @data (Id) VALUES (2, 3)
EXEC [SP_GenerateRegularEmployeeSalary] 2,'20190401','20190430','1',@data
【问题讨论】:
-
旁注:您应该不为您的存储过程使用
sp_前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实会在未来某个时候冒着名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免sp_并使用其他东西作为前缀 - 或者根本没有前缀!
标签: c# entity-framework asp.net-core