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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With