我想返回 ItemNos(字符串)列表,即使很少有字符匹配,即使字符在不同位置匹配。 例如:如果我传入“appl”或“apole”或“daple”。我希望 DB 列出“apple”。
尝试使用levenshteinDistance:(检查编辑次数少于2次的字符串)。
调用计算方法来查找编辑距离 - 使用此链接作为参考:“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'.
我可以知道我哪里出错了。我在代码中调用“Compute”方法是否有问题。
要在本地计算此值,请更改为
public async Task<IEnumerable<string>> GetItemNo(string itemNumber)
{
var itemNumbers = await itemDbContext.Item.Select(p => p.ItemNo).ToListAsync();
return itemNumbers.Where(itemNo => Compute(itemNo , itemNumber) < 2);
}
您可以在 sql 中编写计算代码并使用 FromSqlRaw 方法:
return await itemDbContext.Item.FromSqlRaw("YOUR SQL Query").Select(r=>r.ItemNo).ToListAsync();