c# - 如何检索 Entity Framework 中的特定列

标签 c# .net entity-framework entity-framework-4

我能否让我的 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/

相关文章:

c# - 有没有办法将可观察集合转换为常规集合?

c# - Scala 相当于 C# 中的 `??` 运算符

c# - 在 C# 最佳实践中处理字典

C#:为 ListView 项实现 'filter' 机制的最佳方法是什么?

entity-framework - DDD 和 EF 代码优先迁移

c# - 使用多个 dbcontext 实例和依赖注入(inject)

c# - EF DBConfiguration 自动关联到 DBContext,无需注释

c# - 编译 C# 脚本很慢

.net - WebOrb.net/替代品

c# - 如何使用带有 C# 的 Linq 在 Entity Framework 中获取多个结果集?