实体框架过滤和QUOT;防爆pression<&Func键LT; T,BOOL>>" [英] Entity Framework Filter "Expression<Func<T, bool>>"

查看:227
本文介绍了实体框架过滤和QUOT;防爆pression<&Func键LT; T,BOOL>>"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建实体框架列表过滤方法和更好地理解防爆pression<&Func键LT; ...

I'm trying to create a filter method for Entity framework List and understand better the Expression<Func<...

我有一个这样的测试功能。

I have a Test Function like this.

public IQueryable<T> Filter<T>(IEnumerable<T> src, Expression<Func<T, bool>> pred)
{
    return src.AsQueryable().Where(pred);
}

如果我这样做:

context.Table.Filter(e => e.ID < 500);

或本

context.Table.Filter(e => e.SubTable.Where(et => et.ID < 500).Count() > 0 && e.ID < 500);

这一切运作良好。

it all works well.

但是,如果我这样做:

context.Table.Filter(e => e.SubTable.Filter(et => et.ID < 500).Count() > 0 && e.ID < 500);

或本

context.Table.Where(e => e.SubTable.Filter(et => et.ID < 500).Count() > 0 && e.ID < 500);

我收到一个错误。 LINQ到实体无​​法识别方法...过滤器...

为什么它的工作原理在一种情况下,而不是在加法?我应该在过滤器改变它与相关表的工作。
我preFER从其他外部库的远离是我要的是了解它是如何工作的,并能在将来使用它在任何情况下。

Why it works in one case and not in the adder? What should I change in the Filter for it to work with related tables. I prefer to stay away from other external library's as what I want is to learn how it works and be able to use it in any scenario in future.

在在前两种情况下过滤数据库中正确运行。

In the first two cases the filter runs in the database correctly.

推荐答案

乔恩和蒂姆已经解释了为什么它不能正常工作。

Jon and Tim already explained why it doesn't work.

假设在过滤器code滤波器是不平凡的,你可以改变过滤器,以便它返回一个前pression EF可以翻译。

Assuming that the filter code inside Filter is not trivial, you could change Filter so that it returns an expression EF can translate.

让我们假设你有这样的code:

Let's assume you have this code:

context.Table.Where(x => x.Name.Length > 500);

您现在可以创建方法返回此前pression:

You can now create a method the returns this expression:

Expression<Func<YourEntity, bool>> FilterByNameLength(int length)
{
    return x => x.Name.Length > length;
}

用法是这样的:

context.Table.Where(FilterByNameLength(500));

在内部建立 FilterByNameLength 这位前pression可以任意复杂,只要你可以直接将它传递给其中,

The expression you build inside FilterByNameLength can be arbitrarily complex as long as you could pass it directly to Where.

这篇关于实体框架过滤和QUOT;防爆pression&LT;&Func键LT; T,BOOL&GT;&GT;&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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