Query with Pagedlist

Asked

Viewed 135 times

0

I am using Pagedlist.Mvc for results pagination.

But when doing the following action with the querys:

   public ActionResult Index(int? page, string searchString)
    {
        int pageSize = 10;
        int pageNumber = (page ?? 1);
        var query = db.Grupos.AsQueryable();

        if (!string.IsNullOrWhiteSpace(searchString))
        {
            searchString = searchString.ToUpper();
            query = query.Where(x => x.Nome.ToUpper().Contains(searchString));
        }
        query = query.OrderByDescending(x => x.Id);

        query = query.Select(x => new Grupo
        {
            Id = x.Id,
            Nome = x.Nome
        });
        if (Request.IsAjaxRequest())
        {
            return PartialView("Lista", query.ToPagedList(pageNumber,pageSize));
        }
        return View(query.ToPagedList(pageNumber,pageSize));
    }

I come across the following error when running query.Topagedlist(pageNumber,pageSize):

Additional information: The entity or complex type 'Projeto.Entity.Grupo' cannot be constructed in a LINQ to Entities query.

I would like my query to search only the id and name of this group

  • You do it in a action right ? If yes, put the pagedlist in the return together with the object... Type: query.ToPagedList(1, 10); and see if it works. I think that’s it.

  • @Érikthiago I edited my question, that’s how I’m doing it, and still getting the error =(

  • Is it because you’re using twice the x there in your expressions ? Try to change the lyrics to see if it works. I don’t know, but you are often using the query, may be giving conflict.

  • It is not because I use "x" not...if I remove "Select(x= >new .. it works correctly...

  • I get it. Will using the clause Where wouldn’t solve your problem ? Strange, it seems so simple your expression... I do so when I want to search only two data:Aluno aluno = db.Alunos.Include(x => .Ocorrencias) .AsNoTracking().FirstOrDefault(f => f.AlunoID == id);. And there you make the ordination the way you do there. If you think it is valid to adapt to your scenario.

  • the way you do you search all properties of your class, say, I have a class with 10 properties, Id, name, etc, etc, etc., I want to take only the Id and query, in the database it is faster to select campo1,campo2 from ... than to select * from ...

  • I’m on. But maybe a friend’s answer will do you good !

Show 2 more comments

1 answer

-1

Make that friend:

query = query.Select(i=> new { Id = i.Id, Nome = i.Nome }).Where(x => x.Nome.ToUpper().Contains(searchString));
  • 1

    Can you comment/explain why this solution would be the answer to the question?

  • Hello Rafael, I can not do so, because the name may or may not come, is not mandatory

Browser other questions tagged

You are not signed in. Login or sign up in order to post.