Select in Entity framework with certain columns

Asked

Viewed 2,912 times

3

I’m trying to make a select in a table that contains several columns and I want the command sql that the Entityframework gera contain only the columns I specified.

My code is like this:

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

And my Pository:

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

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

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

3 answers

2

The Entity Framework works with select by default by selecting all columns. If it is still desirable to specify at SQL level which columns should be used, the method SqlQuery of DbSet fulfills that function:

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

2


The problem is when using Ienumerable

The same causes you to search all fields and records, ignoring the LINQ or Lambda methods of the Entity Framework.

To circumvent this, one must use

Iqueryable

It also contributes to performance in queries with the Entity Framework.

-3

See if it helps: 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();
  • It’s exactly the same code I put there in the question...

  • You have to assign, store, select items in an object: servername = recordset.ServerName. You are not doing this

  • Same thing, searched all the columns...

Browser other questions tagged

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