OrderBy& Generic Repository中的OrderByDescending DateTime?

时间:2015-02-12 07:14:16

标签: c# datetime repository entity-framework-6

在我的解决方案中,创建Generic Repository

     public abstract class GenericRepository<C,T> : Repo.IGenericRepository<T>
      where T : class
      where C : DbContext, new(){
       private C _entities = new C();
       public C Context
       {
           get { return _entities; }
           set { _entities = value; }
       }

       public virtual IQueryable<T> GetAll(
        Expression<Func<T,object>> predicate,
        Sorted _sort = Sorted.ASC,
        int _max = 0,
        int _skip = 0
        ) {
            IQueryable<T> query = _sort == Sorted.ASC ? //Sorted is enum
                _entities.Set<T>().OrderBy(predicate).Skip(_skip).Take(_max) :
                _entities.Set<T>().OrderByDescending(predicate).Skip(_skip).Take(_max);

            return query;
       }
    } 

并致电

var db = new JobRepository();
db.GetAll(e=>e.jcudate, sort, a, b).ToList();

错误:

  

无法将类型'System.Nullable`1 [[System.DateTime,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'强制转换为'System.Object'。 LINQ to Entities仅支持转换EDM原语或枚举类型。

但是,如果使用

WSCEntities dbs = new WSCEntities();
dbs.jobservs.OrderBy(e=>e.jcudate).Skip(b).Take(a).ToList();

没问题..,请建议我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

尝试在Func

上使用Expression<Func>委托
public virtual IQueryable<T> GetAll(
        Func<T,object> predicate,
        Sorted _sort = Sorted.ASC,
        int _max = 0,
        int _skip = 0
        ) {
            IQueryable<T> query = _sort == Sorted.ASC ? //Sorted is enum
                _entities.Set<T>().OrderBy(predicate).Skip(_skip).Take(_max) :
                _entities.Set<T>().OrderByDescending(predicate).Skip(_skip).Take(_max);

            return query;
       }

详细了解OrderBy方法的msdn documentation