【问题标题】:Expression... LINQ to Entities only supports casting Entity Data Model primitive types”表达式... LINQ to Entities 仅支持转换实体数据模型原始类型”
【发布时间】:2014-04-21 17:23:55
【问题描述】:

我有这个通用方法:

public IQueryable<TEntity> PaginateAndOrderByDesc<TEntity>(int pageIndex, int pageSize, Expression<Func<TEntity, object>> orderByDescending)
        where TEntity : class, IContextEntity
    {
        int numberOfRecordsToSkip = (pageIndex - 1) * pageSize;

        return context.Set<TEntity>().OrderByDescending(orderByDescending).Skip(numberOfRecordsToSkip).Take(pageSize);
    }

当我使用它时:

List<Person> people = repository.PaginateAndOrderByDesc<Person>(1,
            30, x = > x.RegistrDate)
            .ToList();

我收到一个错误:“无法将类型 'System.DateTime' 转换为类型 'System.Object'。LINQ to Entities 仅支持转换 EDM 基元或枚举类型。”

如何使该通用函数与 orderByDescending 表达式一起使用?

【问题讨论】:

    标签: c# linq entity-framework linq-to-entities


    【解决方案1】:

    添加一个通用参数来表示您订购的类型:

    public IQueryable<TEntity> PaginateAndOrderByDesc<TEntity, TKey>(
        int pageIndex, 
        int pageSize,
        Expression<Func<TEntity, TKey>> sortSelector)
    where TEntity : class, IContextEntity
    {
        int numberOfRecordsToSkip = (pageIndex - 1) * pageSize;
    
        return context.Set<TEntity>()
            .OrderByDescending(sortSelector)
            .Skip(numberOfRecordsToSkip)
            .Take(pageSize);
    }
    

    话虽如此,我建议不要在此查询中包含OrderBy 方法。结合“排序数据”和“获取特定页面”操作会降低查询的可读性。将它们分开。 “订购数据”操作就可以了;你真的只需要创建一个“获取某个页面”查询:

    public static IQueryable<TEntity> GetPage<TEntity>(
        this IOrderedQueryable<TEntity> query,
        int pageIndex,
        int pageSize)
    {
        int numberOfRecordsToSkip = (pageIndex - 1) * pageSize;
    
        return query.Skip(numberOfRecordsToSkip)
            .Take(pageSize);
    }
    

    除了赋予您更大的能力来编写您认为合适的查询之外,更重要的是,这会产生更具可读性的查询,其中发生的事情根据调用的方法非常清楚。

    【讨论】:

    • 非常感谢它的工作!我搜索了一半的互联网,找不到合适的解决方案。你保持简单是对的!
    • 感谢您花时间提到只执行 GetPage 操作。每当您在方法签名中使用“与”或“或”一词时,我总是告诉自己(和其他开发人员),重新考虑您在做什么以及为什么在签名中使用条件短语。如果您使用条件短语,为什么不将它们分开操作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多