简体   繁体   中英

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

var projection = GetPeople().Select(p => new {p.Username, p.Email});

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.

Here:

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>().Select(per => new {per.UserName, per.Email})                
}

and you want to filter resaults, add some overloads for example:

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>().Select(per => new {per.UserName, per.Email})                
}

public IQueryable<Person> GetPeople(int cityId)
{
    return DbContext.Set<Person>().Where(p => p.CityID == cityId)
               .Select(per => new {per.UserName, per.Email})                
}

If you want to retrieve the object person :

Add a constructor in the "Person" class

    public Person(string UserName, string EmailAddress){
      This.UserName = UserName;
      This.EmailAddress = EmailAddress;}

And modify this method

public IQueryable<Person> GetPeople()
{
    return DbContext.Set<Person>()
                    .Select(per => new Person(per.UserName, per.Email));                 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM