Linq查询实体框架核心中的参数转换错误

时间:2019-12-11 12:51:27

标签: c# .net entity-framework linq

对于SEO,我删除土耳其语字符和空格。

但是我不能格式化LINQ参数, 它给出了错误。

  

LINQ表达式'DbSet       哪里(p => p.ProductNameTR           .trCharToEnChar()== __productName_0)'无法翻译。以可以翻译的形式重写查询,或者通过插入对AsEnumerable(),AsAsyncEnumerable(),ToList()或ToListAsync()的调用来显式切换到客户端评估。有关更多信息,请参见https://go.microsoft.com/fwlink/?linkid=2101038

public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter = null)
{
    TContext context = new TContext();
    return filter == null ?
        context.Set<TEntity>().ToList() :
        context.Set<TEntity>().Where(filter).ToList();
}

public static string trCharToEnChar(this string str)
{
    var newStr = "";
    for (int i = 0; i < str.Length; i++)
    {
        newStr = str.Replace(" ", "_");
        newStr = newStr.Replace("ı", "i");
        newStr = newStr.Replace("ö", "o");
        newStr = newStr.Replace("ü", "u");
        newStr = newStr.Replace("ğ", "g");
        newStr = newStr.Replace("ş", "s");
        newStr = newStr.Replace("ç", "c");
        newStr = newStr.Replace("ü", "u");
    }

    return newStr;
}

public List<Products> GetProductsByProductNameTextConvert(string productName)
{
    return _productDal.GetAll(p => p.ProductNameTR.trCharToEnChar() == productName);
}

2 个答案:

答案 0 :(得分:1)

发生此问题是因为您使用的是EF Core 3.0或更高版本,并且EF无法将表达式p => p.ProductNameTR.trCharToEnChar() == productName转换为SQL。

在EF Core 3.0之前,将返回整个数据集,然后通过将表达式应用于结果集并返回过滤后的结果集来进一步过滤。

一种快速解决方案是将_productDal.AsEnumerable()更改为_productDal.ToList(),以强制EF在过滤之前检索数据。 AsEnumerable()不足以使EF在数据库中执行查询。

答案 1 :(得分:0)

由于LINQ不知道如何将trCharToEnChar方法转换为SQL,因此可以使用.ToListAsEnumerable()或错误本身建议的其他方法来解决它。在数据加载后使用.ToList(),使用Linq to Objects对内存中已有的数据执行任何进一步的操作(例如select):

context.Set<TEntity>().AsEnumerable().Where(filter).ToList();
// Or context.Set<TEntity>().ToList().Where(filter).ToList();