Why does Entity Framework throw an exception when changing SqlParameter order?

后端 未结 1 960
一个人的身影
一个人的身影 2021-02-19 18:12

Im using entity framework 4.3 code first for calling stored procedure the way i call the stored procedure is like this:

var parameters = new[]
{
    new SqlParam         


        
1条回答
  •  执笔经年
    2021-02-19 18:22

    It's not because of the parameter order in your parameters object - it's because in your second code snippet you're explicitly passing the @Code value as the first parameter when the SP is expecting a Member INT value.

    var result  = context.Database.SqlQuery("mySpName @Code,  @member,@PageSize,@PageNumber" parameters).ToList();
    

    ...you're passing in "0165210662660001" as the first parameter and the conversion to INT is failing.

    The order of your parameters in your parameters object is irrelevant as EF (ADO.NET actually) will map those parameters to the @parametername values in your query string. So the new SqlParameter("Code","0165210662660001") will be mapped into the @Code position in your query - which int the second code snipped is actually the position for the Member value as expected by the SP.

    However... you can execute a SP using named parameters as well and in that case you can pass the parameters to the SP in any order as below:

    db.Database.SqlQuery("mySpName PageNumber=@PageNumber,Code=@Code,PageSize=@PageSize,Member=@member", parameters).ToList();
    

    You see that I'm not passing the params to the SP in the order they were defined [by the SP] but because they're named I don't have to care.

    For different ways of passing params see: This Answer for some good examples.

    0 讨论(0)
提交回复
热议问题