5

I'm trying to get rows based on a WHERE clause in a DbSet object. I have this:

dbContext.Workers

I can get a list like this:

workers = m.Workers.Where(w => w.BranchId == curUser.BranchId).ToList<Worker>();

But as you can see, it returns a List<Worker> and I can't use methods like workers.Find(WorkerId) with it.

Basically, I'm trying to return a DBSet based on some filter I mean I want to use LINQ on a DBSet class. I want this because I need to use workers.Find(WorkerId) also maybe I will need to update this model. So, I will get a list based on where clause, I will change some values and will use dbContext.SaveChanges(). Is that possible?

Thanks

0

1 Answer 1

5

Where(...) returns an IQueryable, which you can manipulate BEFORE the query runs. ToList() will force execution of the query and put the objects into memory. If you want to 'find' an item AFTER the query then you could do something like this with your List:

workers.SingleOrDerfault(x => x.WorkerId == WorkerId);

If you have them all in memory like this, and make changes, then you will persist those changes with a call to .SaveChanges().

However, if you need to apply more filtering to your IQueryable BEFORE the query hits the database, then you'll want to manipulate the IQueryable BEFORE the call to ToList().

Sign up to request clarification or add additional context in comments.

4 Comments

So even if it's an IQueryable, when i change some values in it, DBSet also gets updated? That seems weird and nice at the same time. I'm trying this now, thanks.
No, while it's IQueryable you don't have records yet, you just have the potential to fetch them from the DB, apply additional filtering, etc. If you want to make changes that get persisted you'll have to execute. Read about Deferred Execution for more info.
Thanks, first i will try your solution and then i will read about it.
Thanks again, it fixed my problem.

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.