Select in entity framework with certain columns

2
I'm trying to make a select in a table that contains several columns and I want the sql the EntityFramework generate contains only the columns that I have 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 fetches all other fields (I'm using Entity Framework Profiler)

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

    
asked by anonymous 08.09.2014 / 15:04

3 answers

1

The problem is when using IEnumerable

It also fetches all fields and records, ignoring the Entity Framework's LINQ or Lambda methods.

To get around this you should use

IQueryable

The same also contributes to performance in queries with the Entity Framework.

    
10.10.2014 / 15:13
1

The Entity Framework works with select having behavior default select all columns. If it is still desirable to specify at SQL level which columns to use, the SqlQuery DbSet method fulfills this function:

using (var entidades = new dbContext())
{                
    var clientes = entidades.Clientes.SqlQuery("select Id, Nome, Email, Telefone 
        from Clientes").ToList();
}
    
09.10.2014 / 20:21
-3

See if help: entity-framework-select-multiple-columns

var dataset2 =
    (from recordset in entities.processlists
     where recordset.ProcessName == processname
     select new
     {
         serverName = recordset.ServerName,
         processId = recordset.ProcessID,
         username = recordset.Username
     }).ToList();
    
08.09.2014 / 15:29