[英]Filtering by an untranslatable method using EF Core 3.1
In a web application with a SQL Server database, I have implemented the data access layer using the "Repository Pattern".在带有 SQL 服务器数据库的 web 应用程序中,我使用“存储库模式”实现了数据访问层。 For filtering a
User
based on its email, I'm using an expression like this:为了根据 email 过滤
User
,我使用如下表达式:
var emailFilter = "user@example.com";
var query = _dbContext.Set<User>().Where(x => x.Email.Normalize() == emailFilter.Normalize());
var result = query.ToListAsync();
But EF Core throws an exception which says:但是 EF Core 抛出一个异常,上面写着:
... could not be translated.
...无法翻译。 Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估
I have more than 200k users in the users' table and I don't want to filter data on the client-side.我的用户表中有超过 20 万个用户,我不想在客户端过滤数据。
The mentioned code is only an example but I mean other use cases with more complex methods.提到的代码只是一个示例,但我指的是其他具有更复杂方法的用例。
Now, how can I use complex functions to filter data on the server-side?现在,如何使用复杂的函数在服务器端过滤数据?
I suggest to you, first normalize your email in db by bulk update:我建议您,首先通过批量更新在 db 中标准化您的 email:
by Z.EntityFramework.Plus.EFCore通过Z.EntityFramework.Plus.EFCore
_dbContext.Set<User>().update(x => new User {Email = x.Email.Normalize()} ;
then然后
emailFilter = ("user@example.com").Normalize();
var query = _dbContext.Set<User>().Where(x => x.Email == emailFilter);
var result = query.ToListAsync();
it's an instance solution
这是一个实例解决方案
For non standard go with plain sql queries...对于带有普通 sql 查询的非标准 go...
var emailFilter = "user@example.com";
var result = await _dbContext.Users.FromSqlRaw($"SELECT * FROM dbo.Users WHERE LOWER(Email) = {emailFilter}").ToListAsync();
Or use Functions或者使用函数
var emailFilter = "user@example.com";
var result = await _dbContext.Users.Where(x => EF.Functions.Like(x.Email, $"%{emailFilter}%")).ToListAsync();
With the penalty of the performance...随着性能的惩罚......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.