Can I put query results direct into a viewmodel using Linq

Viewed 29

Im trying to make a query in a table called "Pessoa", but I wanna put the results into a "ViewModelPessoa", cause I wanna get 1 column of another table using the Include, so I did it this way:

IQueryable<PessoaVM> query = (IQueryable<PessoaVM>)context.Set<Pessoa>()
    .Include(u => u.UnidadeRetirada);

it doesnt show any error on the Visual Studio, but when I start the Web Application and enter this line, I got an exception "Unable to cast object of type 'IncludableQueryable2[WebApiSesc.Models.Pessoa,WebApiSesc.Models.UnidadeRetirada]' to type 'System.Linq.IQueryable`1[WebApiSesc.Models.ViewModels.PessoaVM]"

I also tried to not use implicit convert and put the result in the new View Model object, like this:

query = query.Select(p => new PessoaVM() 
    { 
        id = p.id, 
        cpf = p.cpf, 
        nome = p.nome, 
        nomeSocial = p.nomeSocial, 
        status = p.status, 
        createdDate = p.createdDate, 
        UnidadeRetirada = p.UnidadeRetirada, 
        idTipoDependente = p.idTipoDependente 
    });

but the visual studio says that is not possible to convert

Can you help me?

1 Answers

When you do Select, query changes it's type. Your query should look like this.

var query = context.Set<Pessoa>()
    .Select(p => new PessoaVM() 
    { 
        id = p.id, 
        cpf = p.cpf, 
        nome = p.nome, 
        nomeSocial = p.nomeSocial, 
        status = p.status, 
        createdDate = p.createdDate, 
        UnidadeRetirada = p.UnidadeRetirada, 
        idTipoDependente = p.idTipoDependente 
    });
Related