简体   繁体   English

在带有实体框架的DBSet中选择行

[英]Selecting rows in a DBSet with Entity Framework

I'm trying to get rows based on a WHERE clause in a DbSet object. 我试图获取基于DbSet对象中的WHERE子句的行。 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. 但是正如您所看到的,它返回一个List<Worker> ,我不能将它与workers.Find(WorkerId)一起使用。

Basically, I'm trying to return a DBSet based on some filter I mean I want to use LINQ on a DBSet class. 基本上,我试图基于某个过滤器返回一个DBSet ,这意味着我想在DBSet类上使用LINQ。 I want this because I need to use workers.Find(WorkerId) also maybe I will need to update this model. 我想要这个,因为我需要使用workers.Find(WorkerId)也许我也需要更新此模型。 So, I will get a list based on where clause, I will change some values and will use dbContext.SaveChanges() . 因此,我将获得一个基于where子句的列表,我将更改一些值并使用dbContext.SaveChanges() Is that possible? 那可能吗?

Thanks 谢谢

Where(...) returns an IQueryable, which you can manipulate BEFORE the query runs. Where(...)返回一个IQueryable,您可以在查询运行之前对其进行操作。 ToList() will force execution of the query and put the objects into memory. ToList()将强制执行查询并将对象放入内存。 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(). 如果将它们全部存储在内存中并进行更改,则可以通过调用.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(). 但是,如果在查询命中数据库之前需要对IQueryable进行更多过滤,则需要在调用ToList()之前操纵IQueryable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM