C# 从实体框架动态调用存储过程
给定一个名称,我需要检查EDMX中是否存在具有该名称的存储过程,然后使用其参数运行它 要调用的存储过程由context.Database.SqlQuery找到,查询的参数是通过context.GetQueryParameters(string QueryName)运行已知存储过程找到的 剩下的存储过程名是SQL参数名和类型C# 从实体框架动态调用存储过程,c#,.net,sql,entity-framework,reflection,C#,.net,Sql,Entity Framework,Reflection,给定一个名称,我需要检查EDMX中是否存在具有该名称的存储过程,然后使用其参数运行它 要调用的存储过程由context.Database.SqlQuery找到,查询的参数是通过context.GetQueryParameters(string QueryName)运行已知存储过程找到的 剩下的存储过程名是SQL参数名和类型 提前感谢您的帮助!这让我很难受…很难猜测您使用它到底是为了什么,但基于您使用GetQueryParameters作为进程名,我猜测这是否适用于不同的查询/搜索 如果这些都返回
提前感谢您的帮助!这让我很难受…很难猜测您使用它到底是为了什么,但基于您使用GetQueryParameters作为进程名,我猜测这是否适用于不同的查询/搜索 如果这些都返回相同的类型(搜索结果),并且您希望在EF中执行此操作的原因是强类型,那么您可以执行以下操作: (示例使用EF5和LinqPad中的测试上下文)
使用(var context=newtestentities())
{
字符串procname=“GetPrograms”;
//上下文有方法GetPrograms(int?id)
//方法1-在上下文中使用该方法
//这不会动态工作
IEnumerable result1=context.GetPrograms(4);
结果1.转储(“方法1”);
//方法2-使用反射获取并在上下文上使用方法
//构建参数需要按照它们在方法上的顺序进行
//这会得到一个IEnumerable,但不是强类型的
MethodInfo method=context.GetType().GetMethod(procname);
方法。GetParameters();
列表参数=新列表();
参数。添加(4);
IEnumerable result2=(IEnumerable)方法.Invoke(上下文,参数.ToArray());
结果2.转储(“方法2”);
//Method3-对公共返回类型进行SqlQuery调用,传递一个动态列表
//此返回类型可以是,但不需要是实体类型
var argList=新列表();
Add(新的SqlParameter(“@id”,4));
对象[]prm=argList.ToArray();
var csv=String.Join(“,”,argList.Select(l=>l.ParameterName));
IEnumerable result3=context.Database.SqlQuery(“exec”+procname+“”+csv,prm);
结果3.转储(“方法3”);
}
听起来您最好还是回到ADO.NET提供程序来解决这个问题。并不是说这是不可能的,但这样做的努力将是毫无益处的。是的,不使用EF会容易得多,只需亲自查看数据库即可获取并运行存储过程。谢谢!我一整天都在强调这一点,终于放弃了,像你们说的那样直接进入数据库。这看起来真的很不雅观,因为我只剩下一个数据集(来自sqldataadapter)和一个新的连接字符串,它由一个方法使用。b.t.w.,为什么你的个人资料照片来自色情网站?(我最初发布了NSFW链接,但决定不发布,但这很容易被谷歌搜索到)。对不起,伙计,这张照片都是我的。
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");
}