Entity framework select clause on a dbcontext

c# entity-framework

Question

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

1
3
12/4/2012 7:26:24 PM

Accepted Answer

var projection = GetPeople().Select(p => new {p.Username, p.Email});
9
12/4/2012 7:22:20 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow