Creating Linq Expressions with Variables

I am using Linq and Entity Framework. I have a page object that has a many-to-many relationship to a tag.

I want to create a Linq query that pulls in all pages that match all supplied tags (in the form of Int64 []).

I've tried various examples of WhereIn and BuildContainsExpression but none seem to work as expected.

Now I'm trying to loop through each of the tags and build a list of expressions:

 foreach (Int64 item in Tags)
 {
    Expression<Func<Pages, bool>> tagFilter = c => c.Tags.Any(x => x.TagID == item);
    exp.Add(tagFilter);
 }

      

However, I think the local variable "item" is messing with the request because it either uses one tag or none of them when running the request, however if I specify them like this:

 Expression<Func<Pages, bool>> tagFilter1 = c1 => c1.Tags.Any(x => x.TagID == 70);
 exp.Add(tagFilter1);
 Expression<Func<Pages, bool>> tagFilter2 = c1 => c1.Tags.Any(x => x.TagID == 130);
 exp.Add(tagFilter2);
 Expression<Func<Pages, bool>> tagFilter3 = c1 => c1.Tags.Any(x => x.TagID == 77);
 exp.Add(tagFilter3);

      

Using the actual number "70" for example, it works like a charm. I basically store expressions in a list and use LinqKit for AND ().

Is there a way to keep this dynamic?

+2


source to share


1 answer


Change your code to:

foreach (Int64 item in Tags)
{
    var temp = item; // this variable is scoped **inside** the loop.
    Expression<Func<Pages, bool>> tagFilter = c => c.Tags.Any(x => x.TagID == temp);
    exp.Add(tagFilter);
}

      



For a detailed explanation, read my answer to the question "What is the exact definition of closure?" ... question .

+4


source







All Articles