[英]Entity Framework - Linq to Entities - Optional filter
I am struggling to figure out how to get a LINQ statement to produce a specific WHERE
clause in SQL in a single statement. 我正在努力弄清楚如何在单个语句中获取LINQ语句以在SQL中生成特定的WHERE
子句。
I am after it producing something like this: 我追求的是这样的:
SELECT ColA, ColB, ColC, ColN...
FROM Orders
WHERE Client = @ClientId
AND (@CompanyId IS NULL OR @CompanyId = CompanyId)
My ( failing ) LINQ statement looks like this: 我的( 失败的 )LINQ语句如下所示:
var includeAllCompanies = company == null;
var data = context.Orders.Where(o => o.Client.Id == clientId
&& (includeAllCompanies
|| (c.Company != null && c.Company.Id == company.Id)).ToList();
However, it always throws an exception when the variable company
is NULL ( it works fine when it has been initialised ). 但是,当变量company
为NULL时,它总是会引发异常( 初始化后可以正常工作 )。 The exception being: 例外是:
Non-static method requires a target.
My current fix is to split my LINQ statement into two. 我当前的解决方法是将LINQ语句拆分为两个。 One using an Expression<Func<>>
(to be transformed to a SQL statement with partial filtering). 一种使用Expression<Func<>>
(将转换为带有部分过滤的SQL语句)。 Then another that uses Func<>
to perform the remaining filters on the returned list. 然后是另一个使用Func<>
在返回列表上执行其余过滤器的对象。
Expression<Func<>>
to let SQL do some of the work (excluding nullable objects) Expression<Func<>>
使SQL完成某些工作(不包括可为空的对象)
var data = context.Orders.Where(o => o.Client.Id == clientId).ToList();
Func<>
to then filter out the nullable objects Func<>
然后过滤掉可为空的对象
data = data.Where(c => (territory == null
|| (c.Territory != null && c.Territory.Id == territory.Id))).ToList();
This works, however, I want SQL to be performing this query. 这有效,但是,我希望SQL执行此查询。
The problem is that, company
is server-side variable. 问题是, company
是服务器端变量。 Regardles includeAllCompanies
value, EF has to translate whole LINQ query to SQL - and in this case SQL doesn't know what is company.Id
- so EF has to always get company.Id
value in order to put into SQL query. 考虑到includeAllCompanies
值,EF必须将整个LINQ查询转换为SQL-在这种情况下,SQL不知道什么是company.Id
因此EF必须始终获取company.Id
值才能放入SQL查询。 Even if company
is null (so that is why you get exception). 即使company
为null(这就是为什么您会得到异常)。 I hope you see my point, if not - I'll try to give some sample. 希望您能理解我的意思,否则-我会尝试提供一些示例。
In order get rid of exception you can do the following: 为了摆脱异常,您可以执行以下操作:
var companyId = company == null ? null : (int?)company.Id;
var data = context.Orders.Where(o => o.Client.Id == clientId
&& (companyId == null
|| (c.Company != null && c.Company.Id == companyId)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.