Convert string to Func

c# expression-trees lambda linq

Question

I have the following method

     public List<ServicesLogModel> Paging(Func<ServicesLogModel, bool> condition, string columnOrder, bool? orderDescending, int? pageIndex, int? pageSize, out int total)
    {
         return _mongoRepository.Paging(condition, order => order.Message, orderDescending.Value, pageIndex.Value, pageSize.Value, out total);
    }

The columnOrder parameter is a string as lambda expression (ex: order => order.Message) that I must cast to Func<T, object>

I'm trying with Expression.Parameter

 var parm = Expression.Parameter(typeof(ServicesLogModel), "order");

        var propName = Expression.Property(parm, columnOrder);

        Expression predicateBody = Expression.Assign(parm, propName);


        var test=Expression.Lambda<Func<ServicesLogModel, object>>(predicateBody, parm);

it doesn't work Error :You can not use an expression of type 'System.String' for an assignment to type 'ServicesLogModel'

Edit :Method Signature

public List<T> Paging(Func<T, bool> condition, Func<T, object> order, bool orderDescending, int pageIndex, int pageSize,out int total) 

Call method

    [HttpGet]
    [Route("Admin/GetReaderConnectorLog/{Apikey}/{SecretKey}/{index}/{pagesize}/{orderAsc}/{columnOrder}")]
    public IActionResult GetReaderConnectorLog(string Apikey, string SecretKey, int? index, int? pagesize, bool? orderAsc, string columnOrder)
    {
        try
        {
            _userService.BeginTransaction();
            //  _webApiHelper.ValidateApiKey(Apikey, SecretKey, Context, _userService, true);
            int total;
            //TEST
            var listModel = _connectorLogService.Paging(_ => true, $"order => order.{columnOrder}", orderAsc, index, pagesize, out total);
            _userService.Commit();
            return _webApiHelper.OkResponse($"{_appSettings.Options.UserTag}[Send List User]", Context, new PaginationModel<ServicesLogModel> { ListData = listModel, Total = total, Apikey = Apikey, SecretKey = SecretKey });
        }
        catch (Exception e)
        {
            _userService.Rollback();
            return _webApiHelper.ResolveException(Context, e);
        }
    }

Regards

Popular Answer

Well , the final solution was this

public Func<T, object> GetLambda<T>(string property)
    {
        var param = Expression.Parameter(typeof(T), "p");

        Expression parent = Expression.Property(param, property);

        if (!parent.Type.IsValueType)
        {
            return Expression.Lambda<Func<T, object>>(parent, param).Compile();
        }
        var convert = Expression.Convert(parent, typeof(object));
        return Expression.Lambda<Func<T, object>>(convert, param).Compile();
    }


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why