【发布时间】:2022-10-20 21:02:13
【问题描述】:
我想返回项目列表(字符串),即使很少有字符匹配,即使字符在不同的地方匹配。 例如:如果我传入“apple”或“apple”或“apple”。我希望数据库列出“苹果”。
尝试使用 levenshteinDistance:(检查少于 2 次编辑的字符串)。
调用 Compute 方法查找编辑距离 - 使用此链接作为参考:“https://thedeveloperblog.com/levenshtein”
public async Task<IEnumerable<string>> GetItemNo(string itemNumber)
{
return await itemDbContext.Item
.Where(p => Compute(p.ItemNo, itemNumber) < 2)
.Select(p => p.ItemNo).ToListAsync();
}
返回 InvalidOperationException 错误:
InvalidOperationException: The LINQ expression 'DbSet<Item>()
.Where(s => ItemRepository.Compute(
s: s.ItemNo,
t: itemNumber) < 2)' could not be translated. Additional information:
Translation of method
'ItemApp.Infrastructure.Repository.ItemRepository.Compute' failed. If
this method can be mapped to your custom function, see
https://go.microsoft.com/fwlink/?linkid=2132413 for more information.
Either rewrite the query in a form that can be translated, or switch to
client evaluation explicitly by inserting a call to 'AsEnumerable',
'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.
我可以知道我哪里出错了。我在代码中调用“计算”方法的方式有问题吗?
【问题讨论】:
-
EF 无法为您的
Compute方法创建 SQL。使用ToList()在客户端处理记录。 -
@SvyatoslavDanyliv oof,尽管这意味着每次运行查询时都将整个数据库下载到客户端; where 中没有其他子句可以减少它。这可能很痛苦
-
@CaiusJard,是的,在这一系列相同的问题中错过了重要的投影部分。
标签: c# sql entity-framework-core asp.net-core-webapi