繁体   English   中英

在 Linq 查询 Entity Framework Core 中转换参数时出错

[英]Error converting parameter in Linq query Entity Framework Core

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

但我无法格式化 LINQ 参数,它给出了错误。

无法翻译 LINQ 表达式“DbSet .Where(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);
}

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

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

快速解决方法是将_productDal.AsEnumerable()更改为_productDal.ToList()以强制 EF 在过滤之前检索数据。 AsEnumerable()不足以导致 EF 在数据库上执行查询。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM