1

Consider the following class:

public class Customer
{
    public int Id {get; set;}
    public int GroupId {get; set;}
    public int Number {get; set;}
    public string Name {get; set;}
}

I have a method in the service layer that does:

public Customer Get(Expression<Func<Customer, bool>> where)
{
    return customerRepository.Get(where);
}

The calling code is:

var customer = customerService.Get(x => x.Number == number);

In the above method, the user searches a customer based on a property (excluding GroupId because this is hidden in the ViewModel). However, a user is always assigned to a group, and therefore, he is only allowed to search for customers within his group. So the GroupId must be added dynamically.

How can I add the GroupId to the where expression in the method above. The GroupId may or may not be already available in the expression.

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • look into [predicatebuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) – DLeh Apr 09 '15 at 12:49

1 Answers1

7

Using PredicateBuilder you can help build expressions that you can add onto your calls. This would allow you to do something like below.

public void DoSearch(MyViewModel vm)
{
    Expression<Func<Customer, bool>> myFilter = x => yourCurrentFilterLogic;
    var combined = myFilter.And(x => x.GroupId == vm.GroupId);   //PredicateBuilder extension method
    var customers = Get(combined);
}

public Customer Get(Expression<Func<Customer, bool>> where)
{
    return customerRepository.Get(where);
}
DLeh
  • 23,806
  • 16
  • 84
  • 128
  • 1
    Why do you need the PredicateBuilder and not simply a `.Where(x => x.Id == groupID)?` – xanatos Apr 09 '15 at 13:03
  • i made a better example that shows building a single expression to send to his `Get()` method that shows why I was thinking of `PredicateBuilder`. He didn't provide the code that shows his first expression, so it's not totally clear whether `PredicateBuilder` would be needed or not. – DLeh Apr 09 '15 at 13:08
  • 1
    @xanatos Tried the PredicateBuilder extension. I get the exception: `The LINQ expression node type 'Invoke' is not supported in LINQ to Entities` – Ivan-Mark Debono Apr 10 '15 at 06:14
  • 1
    I've changed the `PredicateBuilder` class as per this answer (http://stackoverflow.com/questions/22406952/keep-getting-the-linq-expression-node-type-invoke-is-not-supported-in-linq-to) and it works like a charm! – Ivan-Mark Debono Apr 10 '15 at 06:24