Create Generic Expression from string property name

后端 未结 1 361
失恋的感觉
失恋的感觉 2020-12-30 02:37

I have a variable called sortColumn, which contains the text of a column that I want to sort a query result by. I also have a generic repository which takes as a parameter

相关标签:
1条回答
  • 2020-12-30 03:20

    You kinda need to use the correct generic overload - which used to mean you had to use MakeGenericMethod; however, you can also use dynamic to avoid the need to use MakeGenericMethod here, for example (in this case via Where, but the important point is how it works):

    IQueryable<Foo> source = new[] { new Foo { Bar = 123 } }.AsQueryable();
    Expression<Func<Foo,bool>> typed =  x=>x.Bar == 123;
    
    LambdaExpression untyped = typed;
    IQueryable<Foo> filtered = Queryable.Where(source, (dynamic)untyped);
    

    Note: you can't use extension methods here - hence why you need to use Queryable.*.

    For an OrderBy example using your code:

    var parameter = Expression.Parameter(typeof(Foo));
    var memberExpression = Expression.Property(parameter, "Bar");
    var lambdaExpression = Expression.Lambda(memberExpression, parameter);
    LambdaExpression untyped = lambdaExpression;
    
    IQueryable<Foo> sorted = Queryable.OrderBy(source, (dynamic)untyped);
    
    var all = sorted.ToArray();
    

    Re the edit:

    var parameter = Expression.Parameter(typeof(IRelationship));
    var memberExpression = Expression.Property(
        Expression.Convert(parameter, typeof(IContract)), data.SortColumn);
    var orderBy = Expression.Lambda(memberExpression, parameter);
    
    0 讨论(0)
提交回复
热议问题