Skip list for model

0

I have a query that returns a list like this:

var list = db.Comentario.Where(d => d.GrupoTrabalhoId == Id).OrderByDescending(s => s.DataComentario).ToList();

After this query, it will return me among other things the user id, I would like to get the name. so I thought about doing a foreach and querying the name for the id of the user, it would look like this:

    foreach (var item in list)
    {
      model.Id = item.Id;
      model.GrupoTrabalhoId = item.GrupoTrabalhoId;
      model.Comentario = item.Comentario;
      model.UsuarioId = item.UsuarioId;
      //ABAIXO EU FARIA A NOVA CONSULTA
      model.NomeUsuario = dbUsuario.Usuarios.Where(d => d.UsuarioID == item.UsuarioId).Select(s => s.Nome).FirstOrDefault();;
      model.DataComentario = item.DataComentario;
    }

Just the way it is this will override every foreach loop.

the complete code looks like this:

[HttpPost]
public ActionResult ListaComentario(int Id)
{

   using (var db = new ContextoComentario())
   {
      var list = db.Comentario.Where(d => d.GrupoTrabalhoId == Id).OrderByDescending(s => s.DataComentario).ToList();

     var model = new ComentarioModel();
     var dbUsuario = new ContextoUsuario();


     foreach (var item in list)
     {
        model.Id = item.Id;
        model.GrupoId = item.GrupoId;
        model.Comentario = item.Comentario;
        model.UsuarioId = item.UsuarioId;
        model.NomeUsuario = dbUsuario.Usuarios.Where(d => d.UsuarioID == item.UsuarioId).Select(s => s.Nome).FirstOrDefault();
        model.DataComentario = item.DataComentario;
      }

       return View(model);
   }
}

------ UPDATED REPOSITORY ------

I did as the colleague talked about below, create a model list and each loop insert a new one. see below. but would not you have another, more elegant way to do that?

var model =  new List<ComentarioModel>();
var dbUsuario = new ContextoUsuario();

foreach (var item in list)
{
   var comentario = new ComentarioModel();
   comentario.Id = item.Id;
   comentario.GrupoTrabalhoId = item.GrupoTrabalhoId;
   comentario.Comentario = item.Comentario;
   comentario.UsuarioId = item.UsuarioId;
   comentario.NomeUsuario = dbUsuario.Usuarios.Where(d => d.UsuarioID == item.UsuarioId).Select(s => s.Nome).FirstOrDefault();
   comentario.DataComentario = item.DataComentario;
    model.Add(comentario);
}
    
asked by anonymous 04.12.2018 / 19:27

1 answer

1

There are several more elegant ways to do this.

But it can be simplified as follows:

var model = list.Select(item => new ComentarioModel
{
   Id = item.Id,
   GrupoTrabalhoId = item.GrupoTrabalhoId,
   Comentario = item.Comentario,
   UsuarioId = item.UsuarioId,
   NomeUsuario = dbUsuario.Usuarios.FirstOrDefault(d => d.UsuarioID == item.UsuarioId),
   DataComentario = item.DataComentario
});
    
04.12.2018 / 21:51