DevWithSigns
DevWithSigns

Reputation: 725

Cannot get data using LINQ in MVC

I'm trying to get data in autocomplete from JsonResult Action Method in my controller. I cannot query data with LINQ, I'm sharing code please guide me.

Action Method

public class VehicleController : Controller
{
        private readonly IService<Vehicle> _service;

        public VehicleController(IService<Vehicle> service)
        {
            _service = service;
        }
    public JsonResult AutoComplete(string term)
    {
       var vehicle = _service.GetAll().Select(c => new { Name = c.Name });
       return Json(vehicle, JsonRequestBehavior.AllowGet);
    }
}

EntityRepository

public class EntityRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
    private readonly IEntitiesContext _context;
    private readonly IDbSet<TEntity> _dbEntitySet;
    private bool _disposed;

    public EntityRepository(IEntitiesContext context)
    {
       _context = context;
       _dbEntitySet = _context.Set<TEntity>();
    }

    public List<TEntity> GetAll()
    {
       return _dbEntitySet.ToList();
    }
}

IRepository

public interface IRepository<TEntity> : IDisposable where TEntity : BaseEntity
{
   List<TEntity> GetAll();
}

Service

public class Service<TEntity> : IService<TEntity> where TEntity : BaseEntity
{
   public IUnitOfWork UnitOfWork { get; private set; }
   private readonly IRepository<TEntity> _repository;
   private bool _disposed;

   public Service(IUnitOfWork unitOfWork)
   {
      UnitOfWork = unitOfWork;
      _repository = UnitOfWork.Repository<TEntity>();
   }

   public List<TEntity> GetAll()
   {
      return _repository.GetAll();
   }
}

IService

public interface IService<TEntity> : IService where TEntity : BaseEntity
{
    List<TEntity> GetAll();
}

Action Method is returning a complete list of data but when I apply any filter it won't work and returns no values -- e.g I tried this and it returns null:

var vehicle = _service.GetAll().Where(c => c.Name.StartsWith(term)).Select(c => new { Name = c.Name });

Upvotes: 0

Views: 453

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

Ensure term matches the case of the data. As all the data is loaded (.ToList() in the DAL), the .Where clause uses .Net comparison rather than SQL comparison:

    var vehicle = _service.GetAll().Where(c => c.Name.StartsWith(term, StringComparison.OrdinalIgnoreCase)...

If, in the future, you want to change this to Contains, you can add an extension method:

    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        if (source == null) throw new ArgumentNullException("source");
        return source.IndexOf(toCheck, comp) >= 0;
    }

then

    var vehicle = _service.GetAll().Where(c => c.Name.Contains(term, StringComparison.OrdinalIgnoreCase)...

Upvotes: 1

Related Questions