实体框架动态Where子句 [英] Entity Framework Dynamic Where Clause

查看:83
本文介绍了实体框架动态Where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个查询:

pre $ var $ function var GetSomeExpression();

using(FooModel context = new FooModel())
{
var bar = context.Bar.Where(function);
}

我想制作一个通用方法,可以针对不同实体执行Where在上下文中。我们的目标不是去做context.Bar.Where,context.Car.Where,Context.Far.Where等。

一些不能完成的事情,但是举例说明我们的目标是:

$ $ p $ var q = context.GetObjectContext(T).Where(queryFunction);

我已经研究过使用Relfection并可以获取Where方法,但不知道如何执行它违背代表传递的内容。



到目前为止:



我也看了DynamicMethod,但是做整个IL的东西并不喜欢吸引力。

 私人列表< T> GetResults< T>(Expression< Func< T,bool>> queryFunction)
{
//注意:first()用于原型,应该比较参数类型
MethodInfo whereMethod = typeof Query).GetMethods()
.Where(m => m.Name ==Where)
.First()。MakeGenericMethod(typeof(T));

//调用该方法并返回结果
List< T> result = whereMethod.Invoke(
//有方法info
//有表达式
//可以引用上下文
);

抛出新的NotImplementedException();
}

这可能吗?



 解决方案

私人列表< T> GetResults< T>(IQueryable< T> source,
Expression< Func< T,bool>> queryFunction)
{
return source.Where(queryFunction).ToList< T> ;
}


I have a query like:

var function = GetSomeExpression();    

using (FooModel context = new FooModel())
{
    var bar = context.Bar.Where(function);
}

I'd like to make a generic method that can execute Where against different Entities in the context. The goal is not having to do context.Bar.Where, context.Car.Where, Context.Far.Where, etc.

Something that cannot be done, but illustrates the goal is:

var q = context.GetObjectContext(T).Where(queryFunction);

I have looked into using Relfection and can get the Where method, but do not know how to execute it against the context passing in the delegate. I also looked at DynamicMethod, but doing the whole IL thing does not like appealing.

What I have so far:

private List<T> GetResults<T>(Expression<Func<T, bool>> queryFunction)
{
    // note: first() is for prototype, should compare param type
    MethodInfo whereMethod = typeof(Queryable).GetMethods()
        .Where(m => m.Name == "Where")
        .First().MakeGenericMethod(typeof(T)); 

    // invoke the method and return the results
    List<T> result = whereMethod.Invoke(
    // have the method info
    // have the expression
    // can reference the context 
    );

    throw new NotImplementedException();
}

Is this possible to do?

解决方案

This is way easier then what I was trying before:

private List<T> GetResults<T>(IQueryable<T> source, 
    Expression<Func<T, bool>> queryFunction)
{
   return source.Where(queryFunction).ToList<T>();
}

这篇关于实体框架动态Where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆