简体   繁体   English

从实体框架过滤数据

[英]Filtering data from Entity Framework

I have simple method where I retrieve data from database and send it to the View. 我有一个简单的方法,可以从数据库中检索数据并将其发送到View。 But in the meantime data need to filtered. 但是与此同时,数据需要过滤。 I have below code: 我有以下代码:

public ActionResult Index(string Name, string Manufacturer)
    {
        var dev = db.Devices;
        if(!String.IsNullOrEmpty(Name))
        {
            dev = dev.Where(w => w.Name.Contains(Name));
        }
        if(!String.IsNullOrEmpty(Manufacturer))
        {
            dev = dev.Where(w => w.Manufacturer.Contains(Manufacturer));
        }
        return View(dev.ToList());
    }

but I'm getting this error: 但我收到此错误:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Entity.DbSet'. 无法将类型“ System.Linq.IQueryable”隐式转换为“ System.Data.Entity.DbSet”。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否缺少演员表?)

I tried adding cast eg: 我尝试添加演员,例如:

(DbSet<Device>)

But didn't helped. 但是没有帮助。 Can anyone suggest me how to modify my code? 谁能建议我如何修改我的代码?

The problem is db.Devices will be a DbSet<Device> collection, not an IQueryable<T> , so on these lines 问题是db.Devices将是DbSet<Device>集合,而不是IQueryable<T> ,因此在这些行上

dev = dev.Where(...)

the Where will return IQueryable<T> and given DbSet<T> can't be implicitly set as IQueryable<T> you get an exception. Where将返回IQueryable<T>并且给定的DbSet<T>不能隐式设置为IQueryable<T>您将获得异常。

What you need to do here is convert your DbSet<T> to an IQueryable<T> and that can be done pretty easily by calling AsQueryable ie 您需要在这里执行的操作是将DbSet<T>转换为IQueryable<T> ,这可以通过调用AsQueryable轻松实现,即

var dev = db.Devices.AsQueryable();

By 通过

var dev = db.Devices;

you declare dev to be of type DbSet<Device> . 您将dev声明为DbSet<Device>类型。 The Where-methods return an IQueryable and therefore, you cannot use the variable dev . Where方法返回一个IQueryable,因此,您不能使用变量dev Change the declaration as follows: 更改声明,如下所示:

var dev = db.Devices.AsQueryable();

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

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