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?
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 });
假设您正在使用EF设计器,请使用实体模型设计图从实体模型中删除[数据]列。
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.