【问题标题】:The LINQ expression could not be translated. Translation of method failed无法翻译 LINQ 表达式。方法翻译失败
【发布时间】: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


【解决方案1】:

要在本地计算,请更改为

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);
}

【讨论】:

  • 返回行显示错误,“字符串不包含 ItemNo 的定义,并且找不到接受字符串类型的第一个参数的可访问扩展方法 ItemNo。
  • 请参阅更新的答案。
猜你喜欢
  • 2022-12-05
  • 2021-12-28
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 2021-11-27
  • 2020-09-29
  • 2021-07-01
相关资源
最近更新 更多