Using the entity framework with a MySQL DB and the model designer doesn't pickup stored proc parameters

前端 未结 7 1946
梦谈多话
梦谈多话 2021-01-13 08:34

I\'ve got the latest Mysql connector that allows you to use the Visual Studio Entity Framework designer. It\'s been working great, but I just added a stored proc.

7条回答
  •  不要未来只要你来
    2021-01-13 09:11

    Here is a little extension we did for doing StoredProcedures on our DbContext:

        public static List ExecuteStoredProcedure(this DbContext dbContext, string storedProcedureName, params object[] parameters)
        {
            string storedProcedureCommand = "CALL " + storedProcedureName + "(";
    
            List augmentedParameters = parameters.ToList();
    
            storedProcedureCommand = AddParametersToCommand(storedProcedureCommand, augmentedParameters);
    
            storedProcedureCommand += ");";
    
            return dbContext.Database.SqlQuery(storedProcedureCommand).ToList();
        }
    
        public static List ExecuteStoredRecursiveProcedure(this DbContext dbContext, string storedProcedureName, params object[] parameters)
        {
            string storedProcedureCommand = "SET max_sp_recursion_depth = " + maxRecursionCount + "; CALL " + storedProcedureName + "(";
    
            List augmentedParameters = parameters.ToList();
    
            storedProcedureCommand = AddParametersToCommand(storedProcedureCommand, augmentedParameters);
    
            storedProcedureCommand += ");";
    
            return dbContext.Database.SqlQuery(storedProcedureCommand).ToList();
        }
    
        private static string AddParametersToCommand(string storedProcedureCommand, List augmentedParameters)
        {
            for (int i = 0; i < augmentedParameters.Count(); i++)
            {
                storedProcedureCommand = AddParameterToCommand(storedProcedureCommand, augmentedParameters, i);
            }
            return storedProcedureCommand;
        }
    
        private static string AddParameterToCommand(string storedProcedureCommand, List augmentedParameters, int i)
        {
            if (augmentedParameters[i].GetType() == typeof(string))
            {
                storedProcedureCommand += "'";
            }
    
            storedProcedureCommand += (augmentedParameters[i].ToString());
    
            if (augmentedParameters[i].GetType() == typeof(string))
            {
                storedProcedureCommand += "'";
            }
    
            if (i < augmentedParameters.Count - 1)
            {
                storedProcedureCommand += ",";
            }
    
            return storedProcedureCommand;
        }
    
        

    提交回复
    热议问题