从实体框架动态调用存储过程

本文关键字:调用 存储过程 动态 框架 实体 | 更新日期: 2023-09-27 18:32:16

给定一个名称,我需要检查我们的 EDMX 中是否存在具有该名称的存储过程,然后使用其参数运行它。

要调用的 sproc 由上下文找到。Database.SqlQuery和查询的参数是通过上下文运行已知的sproc来找到的。GetQueryParameters(string QueryName).

我只剩下一个 sproc 名称,它是 SQL 参数名称和类型。

提前感谢您的帮助! 这已经杀死了我...

从实体框架动态调用存储过程

很难准确猜测您使用它的目的,但基于您使用 GetQueryParameters 作为 proc 名称,我猜测这是如果用于不同的查询/搜索。

如果它们都返回相同的类型(搜索结果),并且要在 EF 中执行此操作的原因是强类型,则可以执行以下操作:(示例在 EF5 和 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");
}