user5273382
user5273382

Reputation: 75

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

Upvotes: 5

Views: 5134

Answers (1)

Colorado Matt
Colorado Matt

Reputation: 349

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

Upvotes: 5

Related Questions