使用 ExecuteSqlCommand 调用存储过程(需要未提供的参数)

Jer*_*erf 4 c# sql-server stored-procedures entity-framework

我正在尝试使用 EF 调用存储过程,context.Database.ExecuteSqlCommand因为我的参数之一是数据表。

以下是该过程的参数:

ALTER PROCEDURE [mySchema].[myProc]
    @customerId INT,
    @indicatorTypeId INT,
    @indicators [mySchema].[IndicatorList] READONLY,
    @startDate DATETIME,
    @endDate DATETIME
Run Code Online (Sandbox Code Playgroud)

这是调用存储过程的 C# 代码:

var indicatorsDt = new DataTable();

indicatorsDt.Columns.Add("Date", typeof(DateTime));
indicatorsDt.Columns.Add("Ongoing", typeof(int));
indicatorsDt.Columns.Add("Success", typeof(int));
indicatorsDt.Columns.Add("Warning", typeof(int));
indicatorsDt.Columns.Add("Error", typeof(int));
indicatorsDt.Columns.Add("Other", typeof(int));

var customerIdParam = new SqlParameter("customerId", SqlDbType.Int);
customerIdParam.Value = customerId;

var typeIdParam = new SqlParameter("indicatorTypeId", SqlDbType.Int);
typeIdParam.Value = typeId;

var startDateParam = new SqlParameter("startDate", SqlDbType.DateTime);
startDateParam.Value = startDate;

var endDateParam = new SqlParameter("endDate", SqlDbType.DateTime);
endDateParam.Value = endDate;

foreach (var indicator in indicators)
{
    indicatorsDt.Rows.Add(indicator.Date, indicator.Ongoing, 
                          indicator.Success, indicator.Warning, 
                          indicator.Error, indicator.Other);
}

var tableParameter = new SqlParameter("indicators", SqlDbType.Structured);
tableParameter.Value = indicatorsDt;
tableParameter.TypeName = "MySchema.IndicatorList";

context.Database.ExecuteSqlCommand("exec MySchema.MyProc", customerIdParam, typeIdParam, tableParameter, startDateParam, endDateParam);
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,提供了所有参数,它们都没有空值,但我总是得到这个SqlException

过程或函数“UpdateIndicators”需要参数“@customerId”,但未提供该参数。

我不知道我错过了什么。是否使用SqlParameter错误?ExecuteSqlCommand即使参数并不重要,也会以相同的顺序提供。

预先感谢。

str*_*t01 7

您正在执行的 SQL 字符串中缺少参数。尝试在名称前添加“@”创建参数,然后将 ExecuteSqlCommand 调用更改为:

context.Database.ExecuteSqlCommand("exec MySchema.MyProc @customerId, @indicatorTypeId, @indicators, @startDate, @endDate", customerIdParam, typeIdParam, tableParameter, startDateParam, endDateParam);
Run Code Online (Sandbox Code Playgroud)