首页 > 解决方案 > 使用带有泛型和 linqkit 的表达式创建 linq 查询

问题描述

我在尝试使用泛型类型进行表达式时遇到了一些麻烦

我想做的是为我的实体类型使用泛型创建一个表达式,因为我想构建一种方法来构建动态查询,如下所示:

 public static void executeQuery()
    {
        using (BookStore context = new BookStore())
        {
            DbSet<Author> table = GetEntity<Author>(context);

            var list =  table.AsExpandable().Where(a => DynamicQueryUtility.GetLastId<Author>().Invoke(a,"AuthorId")<10).ToList();

            foreach (var author in list)
            {
                Console.WriteLine(author.ToString());
            }`enter code here`
        }
    }

我得到下一个例外:

System.InvalidOperationException: 'LINQ 表达式'DbSet() .Where(a => (int)a.GetType().GetProperty("AuthorId").GetValue(obj: a, index: null) < 10)' 不能被翻译。以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。有关详细信息,请参阅 https://go.microsoft.com/fwlink/?linkid=2101038。

我调用的方法是下一个:

public static Expression<Func<TEntity,string, int>> GetLastId<TEntity>()
where TEntity : class
{
   return (x,y) => (int)x.GetType().GetProperty(y).GetValue(x,null);
}

Author 实体只有 2 个属性,AuthorId type int 和 Name type string

标签: c#linqentity-framework-coreexpressionlinqkit

解决方案


推荐阅读