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);
}