3

I was trying to pass orderby clause as a parameter:

public IList<SomeType> GetData(Expression<Func<Customer, object>> order)
{
        if (order==null)
        {
            order =   x => x.PrintOrder ;
        }

        var list = (from c in this.dbContext.Customer
                    where c.Type==1
                    orderby order
                    select new {c.Name }).ToList();

        return list;
}

But this throws an error:

System.InvalidOperationException: could not be translated.
Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList'

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Avinash NG
  • 45
  • 5

2 Answers2

4
public IList<Customer> GetData(Expression<Func<Customer, object>> order = null)
    {

    order ??= x => x.PrintOrder;

    //var list = (from c in this.dbContext.Customer
    //             where c.Type==1
    //          orderby order
    //          select c).ToList();
    
    //may works
    return  this.dbContext.Customer.Where(c => c.Type == 1)
                                   .OrderBy(order)
                                   .ToList();
    }
  • as you can see in my question i have not used extension methods. just i am trying with out extension method. since both approaches are same, just i was wondering why that is not working, and if i modify code if (order==null) { order= x => new { x.PrintOrder,x.Sfix } ; } like this, above code also fails to translate – Avinash NG Aug 05 '21 at 06:14
  • 1
    @AvinashNG You *have* to use method syntax to be able to pass an expression into the query. This answer is correct. You didn't mention the other ordering in your question. – Gert Arnold Aug 05 '21 at 06:44
  • @GertArnold, Yes if you use extension method the above answer is right. as you can see i have tried different approach. – Avinash NG Aug 05 '21 at 06:50
-1

Update: As suggested in the comments, this method is only suitable for LINQ-to-object situations, if connecting to DB use accepted answear instead

Original answear:

This works:

Func<Customer, object> order = (c) => c.PrintOrder;
var list = (from c in this.dbContext.Customer
        orderby order(c)
        select c).ToList();

The difference is in calling the function order(c), instead of just passing it

You could also use this syntax:

Func<Customer, object> order = (c) => c.PrintOrder;
var list = this.dbContext.Customer.OrderBy(order).ToList();

Take a look at this post: How can I do an OrderBy with a dynamic string parameter?

PawZaw
  • 1,033
  • 7
  • 15