简体   繁体   中英

How do I create a generic function that dynamically executes any stored procedure?

Environment:
EF Core and.Net Core 3.1

I'm trying to create a single generic function that will dynamically run any stored procedure and can return anything.

public U ExecuteStoredProcedure(string spName, params SqlParameter[], T someGenericType)

Code:

public abstract class Repository<C, T> : IRepository<T> where T : class where C : DbContext, new()
{
    public DbContext Context { get; set; } = new C();

    public Repository()
    {
        Context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
    }

    public IEnumerable<T> ExecuteStoredProcedure(string spName, params SqlParameter[] parameters)
    {
        if (parameters != null && parameters.Any())
        {
            var paramNames = new List<string>();
            foreach (var param in parameters)
            {
                var name = param.ParameterName;
                if (param.Direction == ParameterDirection.Output)
                {
                    name = $"{param.ParameterName} OUT";
                }
                paramNames.Add(name);
            }
            
            var x = Context.Set<T>().FromSqlRaw($"EXEC {spName} {String.Join(",", paramNames.ToArray())}", parameters);

            return x.ToList();
        }

        return Context.Set<T>().FromSqlRaw($"EXEC {spName}").ToList();
    }

}

If you didn't get an answer for this till now. Please check my approach below

  1. For an efficient way of implementing this, you need to have a standard architecture for your stored procedures. Mainly return modes/types. As you we can have Output parameters, return a value or result sets as return types from a stored procedures. You can have a common method to handle all these returns. This is not too much. I suggest have a default table retuned which carry any errors or message to calling application. This must be last select statement executed in the SP. So that you can handle this table as N-1 th table in data set.

  2. Now for handling all types of input parameters you can have a methods which can handle all usually used data types. This method can create the parameter array or collection required for calling SP.

  3. On top of this if you configure all your SP's with its parameters along with data type in configuration again in a standard structure, you just need to iterate through this and set values for parameter collection creation. This also put into a common method.

Comments please.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM