Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework select clause on a dbcontext

Is it possible to have a select clause on a dbcontext.set. I have the following code that returns all coinsurance of People in a db table and selects all columns.

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>();                
}

I only want to select username and email

like image 630
Wesley Skeen Avatar asked May 15 '26 02:05

Wesley Skeen


2 Answers

var projection = GetPeople().Select(p => new {p.Username, p.Email});
like image 110
Jason Meckley Avatar answered May 17 '26 15:05

Jason Meckley


In both your example, and Jason's example, you should be aware of the fact that you are passing the context-aware object. Further manipulations of data may cause unexpected hits against the database. Also when you are doing a function like DbContext.Set() you are doing the slowest form of database call in EF. For the fastest and most effecient database call you would do as follows:

 public List<GetPersonResult> GetPeople()
 {
       return (from p in dbContext.People
              select new GetPersonResult
              {
                   UserName = p.Username,
                   EmailAddress = p.Email
              }).ToList();
 }

 public class GetPersonResult
 {
       public string UserName{get;set;}
       public string EmailAddress{get;set;}
 }

Raw SQL is the fastest form of EF use. Almost as fast as raw ADO.NET.

like image 34
SASS_Shooter Avatar answered May 17 '26 15:05

SASS_Shooter