简体   繁体   中英

Call stored procedure from Entity Framework dynamically

Given a name, I need to check to see if a stored procedure with that name exists in our EDMX and then run it with its parameters.

The sproc to be called is found by a context.Database.SqlQuery, and the parameters for the query are found by running a known sproc via context.GetQueryParameters(string QueryName).

I'm left with a sproc name, and it's SQL parameter names and types.

Thank you in advance for your help! This has been killing me...

It's hard to guess exactly what you are using this for but based on your use of GetQueryParameters as a proc name, I'm guessing this if for different queries/searches.

If these all return the same type (a search result) and the reason you want to do this in EF is that strong typing, you could do something like the following: (Example uses a test context in EF5 and LinqPad)

using (var context = new TestEntities())
{
    string procname = "GetPrograms";
    // context has method GetPrograms(int? id)

    // Method1 - use the method on the context
    // This won't work dynamically
    IEnumerable<GetPrograms_Result> result1 = context.GetPrograms(4);
    result1.Dump("Method1");

    // Method2 - use reflection to get and use the method on the context
    // Building your parameters needs to be in the order they are on the method
    // This gets you an IEnumerable, but not a strongly typed one

    MethodInfo method = context.GetType().GetMethod(procname);
    method.GetParameters();
    List<object> parameters = new List<object>();
    parameters.Add(4);

    IEnumerable result2 = (IEnumerable) method.Invoke(context,parameters.ToArray());
    result2.Dump("Method2");

    // Method3 - make a SqlQuery call on a common return type, passing a dynamic list
    // of SqlParameters.  This return type can be but dows not need to be an Entity type

    var argList = new List<SqlParameter>();
    argList.Add(new SqlParameter("@id",4));

    object[] prm = argList.ToArray();
    var csv = String.Join(",",argList.Select (l => l.ParameterName));

    IEnumerable<GetPrograms_Result> result3 = context.Database.SqlQuery<GetPrograms_Result>("exec " + procname + " " + csv ,prm);
    result3.Dump("Method3");
}

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