0
I have a query that returns me a list this way:
var list = db.Comentario.Where(d => d.GrupoTrabalhoId == Id).OrderByDescending(s => s.DataComentario).ToList();
After this query, she will return me among other things the User Id, I would like to get the name. then I thought to make a foreach and query the name by the user id, would be 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;
}
only that the way it is it will overlap with each loop of the foreach.
the complete code would look 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 RESPONSE------
I did as the colleague said below, create a model list and each loop insert a new one. see below. but there would be no other more elegant way to do it ?
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);
}
And what is your doubt? Because in
Comentario
you don’t give aInclude
in theUsuarios
?– Barbetta
so the doubt is " the way it is it will overlap with each loop of the foreach "
– Elton
Why do you catch an exception just to throw it again?
– Maniero
Create a model list and with each loop you will insert a new model in the model list.
– Guilherme Caixeta
@Maniero is because was giving error :) . I will take.
– Elton