lundi 13 juillet 2015

Better way to Sort a Queryable by any property

I want to sort before the database query, but I can't do this.

My code:

public virtual DataTablesData<TViewModel> DataTablesGetData(DataTablesParam model)
{
    var paged = new DataTablesData<TViewModel>();
    IQueryable<TEntity> qr;

    try
    {
        using (var db = new EdmxMSSQLContainer())
        {
            List<TViewModel> list = null;

            qr = db.Set<TEntity>();

            int iColumn = model.Order.FirstOrDefault().Column;
            var property = typeof(TEntity).GetProperty(model.Columns.ToArray()[iColumn].Data);
            var param = Expression.Parameter(typeof(TEntity));
            Expression final = Expression.Property(param, property);

            if (property.PropertyType.IsValueType)
            {
                final = Expression.MakeUnary(ExpressionType.Convert, final, typeof(object));
            }

            var lambda = Expression.Lambda<Func<TEntity, object>>(final, param);

            if (model.Order.FirstOrDefault().Dir.Equals("asc"))
            {
                qr = qr.OrderBy(lambda);
            }
            else
            {
                qr = qr.OrderByDescending(lambda);
            }

            // THIS LINE THROW EXCEPTION
            list = Mapper.Map(qr.ToList(), list);

            paged.recordsTotal = this.CountRecords();
            paged.recordsFiltered = list.Count();
            paged.data = list;
        }
    }
    catch (Exception ex)
    {
        OnError(ex);
    }

    return paged;
}

This line throw exception:

list = Mapper.Map(qr.ToList(), list);

Exception:

Unable to cast the type System.Int32 to type System.Object. LINQ to Entities only supports casting EDM primitive or enumeration types

Please help-me!?





Aucun commentaire:

Enregistrer un commentaire