OrderBy & OrderByDescending DateTime In Generic Repository?

c# datetime entity-framework-6 repository

Question

In my Solution, create 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;
       }
    } 

and call

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

error :

Unable to cast the type 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

but, If use

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

No problem at all.., Please suggest how I should solve the problem ?

1
0
2/12/2015 7:14:15 AM

Accepted Answer

Try using Func delegate instead on 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;
       }

for more look at msdn documentation of OrderBy method.

1
2/12/2015 7:20:19 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow