简体   繁体   中英

Filtering data from Entity Framework

I have simple method where I retrieve data from database and send it to the 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'. 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

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.

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

var dev = db.Devices.AsQueryable();

By

var dev = db.Devices;

you declare dev to be of type DbSet<Device> . The Where-methods return an IQueryable and therefore, you cannot use the variable dev . Change the declaration as follows:

var dev = db.Devices.AsQueryable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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