I am currently trying to implement TypeAhead plugin with an API search query. The below code is a snippit I recieved from a udemy class Mosh (https://github.com/mosh-hamedani/vidly-mvc-5/blob/master/Vidly/Controllers/Api/CustomersController.cs). Upon implementing the below code I am receiving the error of
Cannot implicitly convert type 'System.Linq.Iqueryable' to System.Data.Entity.DbSet'. An Explicit conversion exists (are you missing a cast)?
This happens on this line of code
vmrsQuery = vmrsQuery.Where(c => c.Description.Contains(query));
Does anyone else have a workaround to get this to function correctly?
public IHttpActionResult GetVMRS(string query = null)
{
var vmrsQuery = _context.VMRS;
if (!String.IsNullOrWhiteSpace(query))
vmrsQuery = vmrsQuery.ToList().Where(c => c.Description.Contains(query));
var vmrsDtos = vmrsQuery
.ToList()
.Select(Mapper.Map<VMRS, VMRSDto>);
return Ok(vmrsDtos);
}
You shouldn't call ToList()
on your context directly. This will pull every row from the database into memory before executing the where clause.
vmrsQuery = vmrsQuery.ToList().Where(c => c.Description.Contains(query));
should be
vmrsQuery = vmrsQuery.Where(c => c.Description.Contains(query));
Also, you probably need to explicitly define your variable.
var vmrsQuery = _context.VMRS;
should be
IQueryable<VMRS> vmrsQuery = _context.VMRS;
This is because the context could be a DbSet if using Entity Framework.
You could also just put _context.VMRS.AsQueryable()