查询的通用实现 - 无法翻译 LINQ 表达式

Generic implementation of querying - LINQ expression could not be translated

我正在研究在 C# 中使用 ef core 和 linq 查询和分页数据的通用实现。 我知道并非所有内容都可以从 linq 转换为 sql,但我仍然觉得我遗漏了一些东西,而我正在努力实现的目标实际上是可能的。 我有一个基础 class 用于所有 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.

有人知道我错过了什么吗?还是无法通过这种方式查询数据?如果有任何其他方法可以达到预期的效果,我将不胜感激。

这样查询是不行的

因为所有 EF Core 查询转换器在运行时看到的都是这个

public abstract string QueryProperty { get; }

并且没有办法看到这个(实现)

=> Name;

因为它无法访问源代码。它所具有的只是查找 属性 定义(因此名称和类型)的反射,而不是实现 - 您可以自己尝试。

请记住,查询转换不会创建实体实例(因此不会执行代码)——它只是使用来自 class 的元数据、数据注释和流畅的映射来生成服务器端查询(SQL ).

您必须找到另一种方式来提供该信息,而不是使用实体 OOP 技术。它可以是一个单独的 class 描述 TEntity,或者一些 属性 标记(带有自定义属性),最后应该给你 Expression<Func<TEntity, string>> 或者只是 string 属性 要在搜索中使用的名称。在前一种情况下,您将动态地(使用 Expression class)编写表达式

q.{Actual_Property_Name}.Contains(arguments.Query)

以后你会使用专门提供的EF.Property方法

EF.Property<string>(q, Actual_Property_Name).Contains(arguments.Query)