Problems with View Model Implementation

1

I'm trying to use the View Model Pattern concept, but when I'm implementing the compiler it's having a conversion error.

Below is the approach I used:

Viewmodel structure

public class EvolucaoViewModel
{
    public Chamado ChamadoAtual { get; set; }
    public virtual ICollection<Evolucao> Evolucoes { get; set; }
}

Implementation in controller

public ActionResult DetalharChamado(int? id)
{
    EvolucaoViewModel model = new EvolucaoViewModel();

    model.ChamadoAtual = _contexto.Chamados.Find(id);
    model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);

    ViewBag.id_usuario = new SelectList(_contexto.Usuarios, "id_usuario", "nome_usuario", model.ChamadoAtual.id_usuario).OrderBy(p => p.Text);
    ViewBag.id_chamado = id;
    ViewBag.id_setor = new SelectList(_contexto.Setores, "id_setor", "nome_setor", model.ChamadoAtual.id_setor);
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    if (model == null)
    {
        return HttpNotFound();
    }
    return View(model);
}

When I try to do this assignment, the VS shows me the message below:

model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);
  

Error 3 Can not implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.ICollection'. E: \ DevSpace \ Projects \ Albasi.Atende \ Albasi.Atende.Web \ Controllers \ CallController.cs 77 31 Albasi.Atende.Web

What do I need to change?

    
asked by anonymous 31.05.2017 / 21:01

3 answers

3

The Evolucoes property of the ViewModel declares a ICollection and the return of the Where method (at least when applied to a IQueryable ) is always IQueryable , ie you are trying to ICollection receive IQueryable , this is wrong.

You need to convert the return from Where to some type that implements ICollection , such as List or others.

What you need to change is

This line

model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);

To

model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id).ToList();
    
31.05.2017 / 21:03
1

Use the conversion to list ".ToList ()" in the excerpt below:

model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id).ToList();
    
31.05.2017 / 22:00
0

Try this:

model.ChamadoAtual = _contexto.Chamados.Include(i => i.Evolucoes).Find(id);

and remove the

model.Evolucoes = _contexto.Evolucoes.Where(e => e.id_chamado == id);
    
01.06.2017 / 02:02