Is this the correct way to add conditions using LINQ (for database queries)?

asp.net entity-framework-core linq

Question

I have some dynamic conditions that I want to use in my Select clause. So I would like to create a "base query" like "SELECT * FROM TABLE" and after I wuold like to add conditions like "WHERE name = 'Diego' AND ...". I'm using Entity Core, and the solution I found (it's working) is as follows:

//conditions
Expression<Func<Person, bool>> foo = (p => p.Id == 1);
//select
List<Person> people = Db.People.Where(foo).ToList();
//Db is the context, People is the DbSet and Person is the model

I hope there is a simple or standard way to do that, in fact I have tried some, but they haven't worked.

Anyway where can I find a good tutorial about it, from simple to complex?

---------------------- UPDATE -----------------------------

Well, this question has marked as duplicate, but this Multiple .Where() clauses on an Entity Framework Queryable , doesn't worked for me,I don't know why, but the statement executes before the conditions, (if I do the same thing like the answer on the link), and I want to apply the conditions before the first statement execution. Yes I know I must use toList() just at the end, anyway if I do the same thing like the answer on that link, the statement will execute before, and I agree this is very strange.

---------------------- UPDATE -----------------------------

I provide some kind of proof for what I'm talking about in the images below:

Here we have a single statement execution (the result is a single Person object), in this example I'm using the code I've written above.

enter image description here

Here as we can see, the code: queryable = Db.People.Where(p => p.Name.Contains("El"));, is executed (the result is two Person objects), even without the method ToList(), in this example I'm using the suggested code.

enter image description here

Well maybe it's a entity core bug. Anyway this question is not the same of that which was been linked for many reasons.

1
-2
7/18/2018 9:03:21 PM

Accepted Answer

Here as we can see, the code: queryable = Db.People.Where(p => p.Name.Contains("El"));, is executed (the result is two Person objects), even without the method ToList(), in this example I'm using the suggested code.

Sorry but what you are seeing is the fact that you accepted allowing the expression to run. It did NOT run until you opened the results as stated in your own screenshot:

enter image description here

So this is a duplicate, you are just unfamiliar with how the locals/watch windows work.

0
7/18/2018 9:13:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow