我正在使用 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.
有谁知道我错过了什么?还是无法通过这种方式查询数据?如果有任何其他方法可以达到预期的结果,我将不胜感激。
答案 0 :(得分:3)
无法以这种方式查询。
因为所有 EF Core 查询翻译器在运行时看到的都是这个
public abstract string QueryProperty { get; }
并且没有办法看到这个(实现)
=> Name;
因为它无法访问源代码。它所拥有的只是查找属性定义(因此名称和类型)的反射,而不是实现 - 您可以自己尝试。
请记住,查询翻译不会创建实体实例(从而执行代码)——它只是使用来自类的元数据、数据注释和流畅的映射来生成服务器端查询 (SQL)。
您必须找到另一种方式来提供该信息,而不是使用实体 OOP 技术。它可以是一个单独的类,描述 TEntity
,或某些属性标记(带有自定义属性),最后应该为您提供 Expression<Func<TEntity, string>>
或仅 string
属性名称以用于搜索。在前一种情况下,您将动态(使用 Expression
类)组合表达式
q.{Actual_Property_Name}.Contains(arguments.Query)
然后您将使用专门提供的 EF.Property
方法
EF.Property<string>(q, Actual_Property_Name).Contains(arguments.Query)