Lambda or Linq brings me all the field and not just those of the expression

0

Just for learning, understand the section. I made a lambda from a bank with only 6 fields, like this:

 public List<LiberacaoDTO> getAutoriza(int idorcamento)
    {
        var lista = contexto.Liberacoes
       .Where(m => m.IdOrcamento == idorcamento)
       .Select(m => new LiberacaoDTO
       {
           TipoVenda = m.TipoVenda,
           Juros = m.Juros != 0 ? m.Juros : 0,
           Entrada = m.Entrada != 0 ? m.Entrada : 0,
           MaxComi = m.MaxComi,
           Cliente = m.Cliente,
           Filial = m.Filial
       })
       .ToList();

        return lista;
    }

When the service returns, it brings up all the fields. Only those listed in the expression, value, the others have null or 0. But why all the fields and not only those listed in the expression? Below is my service call:

public class LiberacaoController : ApiController
    {
        AutorizadorContext contexto = new AutorizadorContext();
        PedidoLiberacao liberacao = new PedidoLiberacao();

        [AcceptVerbs("Get")]
        public IEnumerable<LiberacaoDTO> getLiberacao()
        {
            return liberacao.getAutoriza(1000012093).AsEnumerable().ToList();
         }
    }
    
asked by anonymous 27.08.2017 / 23:00

1 answer

4

The fields you did not specify in .Select are initialized to their default value. For example, all int fields will have a value of 0, all fields string null value and all DateTime fields will have the value 1/1/0001 12:00:00 AM. >

This happens because .Select creates a new instance of the object LiberacaoDTO .

If you want it to return only the .Select fields you can use an anonymous object in .Select:

.Select(m => new 
 {
     TipoVenda = m.TipoVenda,
     Juros = m.Juros != 0 ? m.Juros : 0,
     Entrada = m.Entrada != 0 ? m.Entrada : 0,
     MaxComi = m.MaxComi,
     Cliente = m.Cliente,
     Filial = m.Filial
 })

The problem with this approach is that you will lose some typing.

    
27.08.2017 / 23:28