Reputation: 1590
Can I make my EF objects retrieve only specific columns in the sql executed?
If I have a column that contains a large amount of data that really slows down the query, how can I have my objects exclude that column from the sql generated?
If my table has Id(int), Name(int), Data(blob), how can I make my query be
select Id, Name from TableName
instead of
select Id, Name, Data from TableName
From the suggestion below, my method is
public List<T> GetBy<T>(DbContext context,Expression<Func<T, bool>> exp, Expression<Func<T,T>> columns) where T : class
{
return dbContext.Set<T>().Where(exp).Select<T,T>(columns).ToList();
}
And I'm calling it like so
List<CampaignWorkType> list = GetBy<CampaignWorkType>(dbContext, c => c.Active == true, n => new { n.Id, n.Name });
i got an error like below.
Cannot implicitly convert type 'AnonymousType#1' to 'Domain.Campaign.CampaignWorkType'
how i can solve this?
Upvotes: 2
Views: 4156
Reputation: 1590
The solution is:
First, define a surrogate type:
public class CampaignWorkTypesSimpleList
{
public int Id { get; set; }
public string Name { get; set; }
}
Then change generic method like this:
public List<U> GetBy<T,U>(DbContext context,Expression<Func<T, bool>> exp, Expression<Func<T,U>> columns)
where T : class
where U : class
{
return dbContext.Set<T>().Where(exp).Select<T, U>(columns).ToList();
}
Finally, execute it.
List<CampaignWorkTypesSimpleList> list = this.GetBy<CampaignWorkType, CampaignWorkTypesSimpleList>(dbContext, c => c.Active == true, n => new CampaignWorkTypesSimpleList { Id = n.Id, Name = n.Name });
Upvotes: 9
Reputation: 9191
Assuming you are using the EF designer, remove the [Data] column from the Entity Model using the Entity Model design surface.
Upvotes: -2