【发布时间】:2021-07-26 15:06:00
【问题描述】:
我正在使用 c# 中的 ef core 和 linq 进行查询和分页数据的通用实现。
我知道并非所有内容都可以从 linq 转换为 sql,但我仍然觉得我遗漏了一些东西,而我想要实现的目标实际上是可能的。
我有一个所有实体的基类QueryProperty
public class EntityBase
{
public abstract string QueryProperty { get; }
}
每个实体都会覆盖此属性并引导我们找到我们想要搜索的属性。
public class ChildEntity : EntityBase
{
public string Name { get; set; }
public override string QueryProperty => Name;
}
这是我用来查询和分页的方法
private IQueryable<TEntity> Paginate<TEntity>(IQueryable<TEntity> queryable, PaginationArguments arguments) where TEntity : EntityBase
{
return queryable
.Where(q => q.QueryProperty.Contains(arguments.Query))
.Skip((arguments.Page - 1) * arguments.PerPage).Take(arguments.PerPage);
}
这种实现会导致The LINQ expression could not be translated.异常。完整的例外:
System.InvalidOperationException: The LINQ expression 'DbSet<ChildEntity>.Where(l => l.QueryProperty.Contains("new"))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
有人知道我错过了什么吗?还是无法通过这种方式查询数据?如果还有其他方法可以达到预期的效果,我将不胜感激。
【问题讨论】:
-
显示完整异常。
标签: c# linq entity-framework-core asp.net-core-3.1 ef-core-3.1