Foreach repeating values when running sqlquery

Asked

Viewed 74 times

0

While executing my foreach, he is repeating my first result in sql.

For example:

  1. In doing select * from tbNome he returns Gabriel, Rafael
  2. When executing the sqlquery, he list Gabriel, Gabriel

    List<TbListaNome> lstViewModel= new List<TbListaNome>();
    
    var lista = db.TbListaNome.SqlQuery.("Select * from TbNome").ToList<TbListaNome>();
    foreach(var item in lista)
    {
           NomesViewModel viewModel = new NomesViewModel();
           viewModel .nome = item.nome;
          lstViewModel.add(viewModel);
    }
    return View(viewModel)
    

    ;

TbListaNome is db set

NomesViewModel is my model view

  • Are you selecting the correct table? Your select is selecting the Tbname table. Your template, already named as Tblistaname

  • Fix here but keep repeating and the weirdest it returns the same amount of my select and replaced by the first record

2 answers

0

friend, I made a test here using the same logic as yours, I just changed the command to run the query by Fromsql and it worked perfectly, all 26 state and 1 DF, when adding in the list tbm works perfectly.

            List<UF> list = new List<UF>();
            var uf = _context.UF.FromSql("select * from UF").ToList();

            foreach(var item in uf)
            {
                UF estado = new UF();
                estado._UF = item._UF;
                list.Add(estado);
            }

UF is Federative Unit;

_UF is the name of the state in the UF class;

perform this simple modification, and see if the error continues... if you continue to let me know please

0

Thanks for the tip Dfernandes, I solved using Sqldatareader while(reader.Read()) { pessoaViewModel p1 = new pessoaViewModel(); p1.nome = reader["TbNome"].toString(); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.