0

I'm trying to create an expression in order to retrieve a Store object that should be on a list of countries and also that their Store.Id = X.

I'm trying to do that with the following expression, but that returns all Stores stored on the database, I don't know what I'm missing.

public Expression<Func<Store, bool>> CreateExpression(List<Country> countries, long storeId)
{
    var predicate = PredicateBuilder.False<Store>();

    predicate = countries.Aggregate(predicate, (current, p) => 
        current.Or(e => e.Country.Id == p.Id));

    predicate = predicate.And(e => e.Id == storeId);

    return predicate;
}
ppalms
  • 394
  • 2
  • 7
  • 19
user1520494
  • 1,134
  • 2
  • 11
  • 27
  • 1
    Is it because you're ORing all your `e.Country.Id == p.Id`, if this is true, no other predicate matters. However as you start with False and none of the ORs are true, you will get nothing as `false && something == false` – Ben Robinson Sep 15 '14 at 14:37
  • Ookey, ty for the explanation Ben! but, could you please give me an example? – user1520494 Sep 15 '14 at 15:05
  • `if(false || a == 1 || b == 2 && c ==3)` If a is 1 or b is 2 it doesn't matter what c is, the expression will be true. if c is 3 and a is not 1 and b is not 2 then the expression is false as `if(false && true) ` is `false`. – Ben Robinson Sep 15 '14 at 15:09
  • haha ty that was nice, But I was asking how to create the expression, I mean, I have to create for example predicate.And( e=> (e.Id == storeId) && "here check that the country.Id is inside the list?") – user1520494 Sep 15 '14 at 15:12
  • 1
    I was just explaining why your code gives the results it does. I think what you need to do is nest your ORs in an inner predicate i.e. logically `if((a == 1 || b == 2) && c ==3)`, instructions here http://www.albahari.com/nutshell/predicatebuilder.aspx You probably also want to start out with `var predicate = PredicateBuilder.True();` otherwise you might end up with no records. – Ben Robinson Sep 15 '14 at 15:18

0 Answers0