0

At runtime I have a dynamic list of "Parent" ids i need to query against one of my entity tables, using LINQ how would I generate the query at run time? Currently am (VERY SLOWLY) looping over my list of ID's and performing a separate query to the database using the Where method. Is there an API that will allow me to build a single WHERE statement that in essence is appending "&& value = something" as I would have if I was writing the SQL myself?

Currently what i do looks like this

            foreach(var parent in parents)
        {
            col.AddRange(context.LocalAuthorities.Where(c => c.Parent.ID == parent.ID).ToList());
        }
2
  • Please, add more details. What is your current query? Commented Apr 13, 2015 at 18:59
  • will add an example. Commented Apr 13, 2015 at 19:18

1 Answer 1

1

If your goal is to replace multiple iterative queries by one query, you can use this approach:

var allParentIds = parents.Select(p=>p.ID).ToList();
var result = context.LocalAuthorities.Where(c=> allParentIds.Contains(c.Parent.ID));

col.AddRange(result);
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't think entity framework could translate a contains method call. I know this works with linq to objects, I will try this and get back to you. :)
Perfect and simple, i guess i should have checked before assuming it would not works. Much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.