简体   繁体   English

实体框架和扩展方法中的委托

[英]Entity Framework and delegates in extension methods

Recently I faced a problem with using delegates as predicates in LINQ extensions with EF. 最近,我遇到了在EF的LINQ扩展中将委托用作谓词的问题。 Here is a simple example. 这是一个简单的例子。

Func<LmsIdentityUser, bool> predicate = u => u.FullName.Contains(val) || u.EmployeeId.Contains(val);
var result = _ctx.Users.Where(predicate).ToList();
var result2 = _ctx.Users.Where(u => u.FullName.Contains(val) || u.EmployeeId.Contains(val)).ToList();

I expected that both queries should produce identical SQL query because predicate used in Where() is the same. 我希望两个查询都应产生相同的SQL查询,因为在Where()使用的谓词是相同的。 The only difference is that in the first case it is defined using a delegate. 唯一的区别是,在第一种情况下,它是使用委托定义的。 But here are actual SQL queries generated by EF for these cases. 但是以下是EF针对这些情况生成的实际SQL查询。

Case 1 (using delegate) 案例1(使用委托)

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[EmployeeId] AS [EmployeeId], 
[Extent1].[FullName] AS [FullName]    
FROM [dbo].[AspNetUsers] AS [Extent1]

Case 2 (using lambda directly) 案例2(直接使用lambda)

SELECT TOP (15) 
[Extent1].[Id] AS [Id], 
[Extent1].[EmployeeId] AS [EmployeeId], 
[Extent1].[FullName] AS [FullName]
FROM [dbo].[AspNetUsers] AS [Extent1]
WHERE ([Extent1].[FullName] LIKE @p__linq__0 ESCAPE N'~') OR ([Extent1].[EmployeeId] LIKE @p__linq__1 ESCAPE N'~')

So the question is what is wrong with delegates? 所以问题是代表有什么问题? What should I do to use them in LINQ extensions? 我应该怎么做才能在LINQ扩展中使用它们?

Delegates are of the form Func<Input, Output> whereas LINQ queries are Expression<Func<Input, Output>> . 委托的形式为Func<Input, Output>而LINQ查询为Expression<Func<Input, Output>> LINQ parses the expression to generate a query whereas the delegate acts on the data returned by the SELECT query. LINQ解析表达式以生成查询,而委托则对SELECT查询返回的数据进行操作。 Note there's no filtering at all for the delegate version. 请注意,对于委托版本,根本没有任何过滤。

I believe you could change your predicate to be an Expression<Func<>> to get the behaviour you're looking for though. 我相信您可以将谓词更改为Expression<Func<>>来获得所需的行为。

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

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