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

后端 未结 10 1779
梦谈多话
梦谈多话 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:50

    This solution is (only) for SQL Server 2005

    You guys are lifesavers, but as @Dan Mork said, you need to add EXEC to the mix. What was tripping me up was:

    • 'EXEC ' before the Proc Name
    • Commas in between Params
    • Chopping off '@' on the Param Definitions (not sure that bit is required though).

    :

    context.Database.SqlQuery<EntityType>(
        "EXEC ProcName @param1, @param2", 
        new SqlParameter("param1", param1), 
        new SqlParameter("param2", param2)
    );
    
    0 讨论(0)
  • 2020-11-22 17:54

    You should supply the SqlParameter instances in the following way:

    context.Database.SqlQuery<myEntityType>(
        "mySpName @param1, @param2, @param3",
        new SqlParameter("param1", param1),
        new SqlParameter("param2", param2),
        new SqlParameter("param3", param3)
    );
    
    0 讨论(0)
  • 2020-11-22 17:55
    db.Database.SqlQuery<myEntityType>("exec GetNewSeqOfFoodServing @p0,@p1,@p2 ", foods_WEIGHT.NDB_No, HLP.CuntryID, HLP.ClientID).Single()
    

    or

    db.Database.SqlQuery<myEntityType>(
        "exec GetNewSeqOfFoodServing @param1, @param2", 
        new SqlParameter("param1", param1), 
        new SqlParameter("param2", param2)
    );
    

    or

    var cmdText = "exec [DoStuff] @Name = @name_param, @Age = @age_param";
    var @params = new[]{
       new SqlParameter("name_param", "Josh"),
       new SqlParameter("age_param", 45)
    };
    
    db.Database.SqlQuery<myEntityType>(cmdText, @params)
    

    or

    db.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
    new object[] { param1, param2, param3 }).ToList();
    
    0 讨论(0)
  • 2020-11-22 17:56

    I use this method:

    var results = this.Database.SqlQuery<yourEntity>("EXEC [ent].[GetNextExportJob] {0}", ProcessorID);
    

    I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.

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