entity-framework-6 – Select on entity framework with certain columns

Question:

I'm trying to do a select on a table that contains several columns and I want the sql command that the EntityFramework generates to contain only the columns that I specified.

My code looks like this:

var clientes = (from cliente in repositoryCliente.GetAll()
    select new
    {
        cliente.Id,
        cliente.Nome,
        cliente.Email,
        cliente.Telefone
    }).ToList();

And my repository:

public virtual IEnumerable<T> GetAll()
{
    return _dbSet;
}

But when parsing the sql command it does, it looks for all the other fields (I'm using Entity Framework Profiler)

I want it to run only the sql command "Select Id,Nome,Email,Telefone from Cliente" , and not with the other columns.

Answer:

The Entity Framework works with select having as a behavior pattern select all columns. If it is still desirable to specify at the SQL level which columns should be used, the SqlQuery method of DbSet fulfills this function:

using (var entidades = new dbContext())
{                
    var clientes = entidades.Clientes.SqlQuery("select Id, Nome, Email, Telefone 
        from Clientes").ToList();
}
Scroll to Top