【问题标题】:Generic implementation of querying - LINQ expression could not be translated查询的通用实现 - 无法翻译 LINQ 表达式
【发布时间】: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&lt;ChildEntity&gt;.Where(l =&gt; 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


【解决方案1】:

这样查询是不行的。

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

public abstract string QueryProperty { get; }

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

=> Name;

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

请记住,查询翻译不会创建实体实例(因此执行代码) - 它只是使用类中的元数据、数据注释和流畅的映射来生成服务器端查询 (SQL)。

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

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

稍后您将使用专门提供的EF.Property 方法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    相关资源
    最近更新 更多