1

I need add And && Or same query

This is my code

        var predicate = PredicateBuilder.True<Summon>();
        if (!string.IsNullOrEmpty(param.id))
        {
            predicate = predicate.And(m => m.id== param.id);
        }
        if (!string.IsNullOrEmpty(param.subjects))
        {
            var subjectsPredicate = PredicateBuilder.False<Summon>();
            string[] subjects = param.subjects.Split(',');
            for (int i = 0; i < subjects.Length; i++)
            {
                subjectsPredicate = subjectsPredicate.Or(m => m.SubjectId ==subjects[i]);
            }
            predicate = predicate.And(subjectsPredicate);
        }

My Problem is that when the subjects exist I got an error, all other queries work good just this "sub-query" make the query to fail.

This is my error, If subjects exist. enter image description here

24sharon
  • 1,859
  • 7
  • 40
  • 65
  • You might want to look at [How to construct Order By Expression dynamically in Entity Framework](http://stackoverflow.com/questions/34906437/how-to-construct-order-by-expression-dynamically-in-entity-framework). – Win Feb 24 '16 at 22:06

1 Answers1

0

The solution is simple - Not using the array on the search query subjects[i] - Does not work

instead of write

for (int i = 0; i < subjects.Length; i++)
     {
        subjectsPredicate = subjectsPredicate.Or(m => m.SubjectId ==subjects[i]);
     }

Neet to write

 foreach (string key in subjects)
    {
      subjectsPredicate = subjectsPredicate.Or(m => m.SubjectId == key);
  }
24sharon
  • 1,859
  • 7
  • 40
  • 65
  • I don't really understand. The `for` version of your code should throw an exception like *The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities.* An IndexOutOfRangeException tells that `i` is not an existing index in the `subjects` array, which doesn't seem possible in your code. – Gert Arnold Feb 25 '16 at 18:34