jeudi 17 décembre 2015

Return Func

I have the below method. It returns expression which is called by my repository Get method

  public Func<IQueryable<Level>, IOrderedQueryable<Level>> GetOrderByExpression()
    {
        if (request == null)
        {
            request = new OrderByRequest
            {
                IsAscending = true,  PropertyName = "Name"  // CreatedDate , LevelNo etc
            };
        }
        if (string.IsNullOrWhiteSpace(request.PropertyName))
        {
            request.PropertyName = "Name";
        }
        Type entityType = typeof(Level);
        ParameterExpression parameterExpression = Expression.Parameter(entityType, "x");
        PropertyInfo propertyInfo = entityType.GetProperty(request.PropertyName);
        Expression<Func<Level, object>> sortExpression =
            Expression.Lambda<Func<Level, object>>(
                Expression.Convert(Expression.Property(parameterExpression, request.PropertyName),
                    Type.GetType(propertyInfo.PropertyType.FullName)), parameterExpression);

        Func<IQueryable<Level>, IOrderedQueryable<Level>> expression = request.IsAscending
            ? (Func<IQueryable<Level>, IOrderedQueryable<Level>>)(x => x.OrderBy(sortExpression))
            : (x => x.OrderByDescending(sortExpression));
        return expression;
    }

Repository is calling like below (removed unnecessary codes for clarity):

public virtual IQueryable<TEntity> Get(
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
{
     var query = DbContext.Set<TEntity>().AsQueryable();
      if (orderBy != null)
                {
                    query = orderBy(query);
                }
}

The above method is working perfectly for string type of properties of Level class. But for the other types (like Integer/DateTime etc) it is not working and throwing error

Expression of type 'System.Int32' cannot be used for return type 'System.Object'

I want to make this method a generic OrderByExpression provider, and it will take the property names at runtime (this name will come from client side), so that it can work with any property of that given object. Is it possible?





Aucun commentaire:

Enregistrer un commentaire