使用Entity Framework使用动态参数执行SQL Server存储过程

时间:2013-12-07 08:03:51

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

我们希望使用EF执行存储过程。

我们的方法是动态提供输入参数,如下所示:

PropertyInfo[] props = search.GetProperties();

foreach (var item in props)
{
     object itemValue = item.GetValue(SearchCondition, null);

     if (itemValue == null)
        parameterList.Add(new SqlParameter(string.Format("@{0}", item.Name), DBNull.Value));
     else
        parameterList.Add(new SqlParameter(string.Format("@{0}", item.Name), itemValue.ToString()));
}

以下是其他常见输入:

parameterList.Add(new SqlParameter("@order", (object)"desc"));
parameterList.Add(new SqlParameter("@Page", page));
parameterList.Add(new SqlParameter("@PageSize", rows));

并输出参数:

parameterList.Add(new SqlParameter()
{
    DbType = DbType.Int32,
    ParameterName = "@TotalCount out",
    SqlValue = DBNull.Value,
    Direction = ParameterDirection.Output
});

这里是执行代码(运行存储过程)

object[] para= parameterList.ToArray<object>();

var records = context.Database.SqlQuery<CustomerInformationReturnedList>(string.Format(@"Exec RTI.RptCustomerInformation {0}", parameters), para).ToList();

当我们运行它时会有一个例外:

  

int

附近的语法不正确

这是我们在SQL中执行的存储过程,它在SQL Server Management Studio中正确运行:

EXEC    @return_value = [RTI].[RptCustomerInformation]
    @AccountNumber = NULL,
    @CardNumber = NULL,
    @CustomerNumber = NULL,
    @CustomerType = NULL,
    @NationalNumber = NULL,
    @Name = NULL,
    @FamilyName = NULL,
    @IdentityNumber = NULL,
    @IdSerial = NULL,
    @NationalityType = NULL,
    @InhabitancyType = NULL,
    @JobType = NULL,
    @c13 = NULL,
    @CustomerDefined = NULL,
    @OpenerBranch = NULL,
    @CodePosti = NULL,
    @RegisterNumber = NULL,
    @order = NULL,
    @Page = NULL,
    @PageSize = NULL,
    @TotalCount = @TotalCount OUTPUT

SELECT  @TotalCount as N'@TotalCount'

0 个答案:

没有答案