The entity or complex type '*' can not be constructed in a LINQ to Entities query

6

I can not do this?

public List<Filial> GetAll()
{
    //Mostra todos os registros incluindo os desativados para os Administradores
    var ret = _db.Filiais.AsNoTracking()
                 .Where(e => e.Visible)
                 .OrderBy(e => e.FilialNome)
                 .Select(x => new Filial
                 {
                     FilialId = x.FilialId,
                     FilialNome = x.FilialNome,
                     FilialEndereco = x.FilialEndereco,
                     FilialBairro = x.FilialBairro,
                     FilialFixPhone = x.FilialFixPhone
                  }).ToList();

    return ret;
}

the error

  

The entity or complex type 'CCValemixEF.Infra.Data.Context.Filial'   can not be constructed in a LINQ to Entities query.

    
asked by anonymous 07.02.2017 / 15:48

1 answer

6

That's right, you can not. The error itself says

  The entity or complex type 'CCValemixEF.Infra.Data.Context.Filial' can not be constructed in a LINQ to Entities query.

Free Translation

  

The entity or complex type 'CCValemixEF.Infra.Data.Context.Filial' can not be created in a query LINQ to Entitites

The correct thing is to bring the data into memory, using .ToList() to build the objects later.

Make sure you always leave ToList() after Where() and OrderBy() so that data is filtered and sorted even in the database, not in memory.

var ret = _db.Filiais.AsNoTracking()
             .Where(e => e.Visible)
             .OrderBy(e => e.FilialNome)
             .ToList()
             .Select(x => new Filial
             {
                 FilialId = x.FilialId,
                 FilialNome = x.FilialNome,
                 FilialEndereco = x.FilialEndereco,
                 FilialBairro = x.FilialBairro,
                 FilialFixPhone = x.FilialFixPhone
             }).ToList();
    
07.02.2017 / 15:53