Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting rows in a DBSet with Entity Framework

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

like image 427
user5273382 Avatar asked Aug 31 '15 16:08

user5273382


1 Answers

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().

like image 194
Colorado Matt Avatar answered Nov 01 '22 22:11

Colorado Matt