0

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?

1

2 Answers 2

5

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 i.e.

var dev = db.Devices.AsQueryable();
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

You mean IQueryable<Device>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.