繁体   English   中英

从Entity Framework动态调用存储过程

[英]Call stored procedure from Entity Framework dynamically

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

通过context.Database.SqlQuery查找要调用的sproc,并通过context.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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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