How to use DbContext.Database.SqlQuery(sql, params) with stored procedure? EF Code First CTP5

后端 未结 10 1878
梦谈多话
梦谈多话 2020-11-22 16:53

I have a stored procedure that has three parameters and I\'ve been trying to use the following to return the results:

context.Database.SqlQuery

        
10条回答
  •  情深已故
    2020-11-22 17:42

    Most answers are brittle because they rely on the order of the SP's parameters. Better to name the Stored Proc's params and give parameterized values to those.

    In order to use Named params when calling your SP, without worrying about the order of parameters

    Using SQL Server named parameters with ExecuteStoreQuery and ExecuteStoreCommand

    Describes the best approach. Better than Dan Mork's answer here.

    • Doesn't rely on concatenating strings, and doesn't rely on the order of parameters defined in the SP.

    E.g.:

    var cmdText = "[DoStuff] @Name = @name_param, @Age = @age_param";
    var sqlParams = new[]{
       new SqlParameter("name_param", "Josh"),
       new SqlParameter("age_param", 45)
    };
    
    context.Database.SqlQuery(cmdText, sqlParams)
    

提交回复
热议问题