我能否让我的 EF 对象仅检索执行的 sql 中的特定列?
如果我有一个包含大量数据的列确实会减慢查询速度,我怎样才能让我的对象从生成的 sql 中排除该列?
如果我的表有 Id(int), Name(int), Data(blob),我怎样才能让我的查询成为
select Id, Name from TableName
代替
select Id, Name, Data from TableName
根据下面的建议,我的方法是
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();
}
我是这样调用它的
List<CampaignWorkType> list = GetBy<CampaignWorkType>(dbContext, c => c.Active == true, n => new { n.Id, n.Name });
我收到如下错误。
无法将类型“AnonymousType#1”隐式转换为“Domain.Campaign.CampaignWorkType”
我该如何解决这个问题?
最佳答案
解决方法是:
首先,定义一个代理类型:
public class CampaignWorkTypesSimpleList
{
public int Id { get; set; }
public string Name { get; set; }
}
然后像这样改变泛型方法:
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();
}
最后,执行。
List<CampaignWorkTypesSimpleList> list = this.GetBy<CampaignWorkType, CampaignWorkTypesSimpleList>(dbContext, c => c.Active == true, n => new CampaignWorkTypesSimpleList { Id = n.Id, Name = n.Name });
关于c# - 如何检索 Entity Framework 中的特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10626592/