Search code examples
.netstored-proceduresmodel-view-controllercode-first

stored procedure only executes with Count


I have a Stored Procedure which I call exactly like all my others (which work fine) but it only seems to be executed when I add Count() to it...

This is my controller code:

        public static void SaveGridLayout(string userName, string gridViewId, string layoutData)
    {
        using (var context = new Entities())
        {
            var userNameParam = new SqlParameter("@user_name", userName);
            var gridViewIdParam = new SqlParameter("@grid_id", gridViewId);
            var layoutParam = new SqlParameter("@layout", layoutData);

            context.Database.SqlQuery<UserGridLayoutsEntity>("sp_SaveLayout @user_name, @grid_id, @layout", userNameParam, gridViewIdParam, layoutParam);
        }
    }

This does not give any result, but when I change the last line to:context.Database.SqlQuery<UserGridLayoutsEntity>("sp_SaveLayout @user_name, @grid_id, @layout", userNameParam, gridViewIdParam, layoutParam).Count(); it does and the SP is executed. It would be nice to somehow not have to add count and have the procedure executed right from the start. Thanks!


Solution

  • public static void SaveGridLayout(string userName, string gridViewId, string layoutData)
    {
        using (var context = new Entities())
        {
            var userNameParam = new SqlParameter("@user_name", userName);
            var gridViewIdParam = new SqlParameter("@grid_id", gridViewId);
            var layoutParam = new SqlParameter("@layout", layoutData);
    
            context.Database.ExecuteSqlCommand("sp_SaveLayout @user_name, @grid_id, @layout", userNameParam, gridViewIdParam, layoutParam);
        }
    }
    

    I think you can execute it directly like this. With .SqlQuery you can even use .ToList() if not .Count() but executesqlcommand should do a good job in you case.