如何检索实体框架特定的列 [英] How to retrieve specific columns in Entity Framework

查看:103
本文介绍了如何检索实体框架特定的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以让我的EF对象检索在SQL只有特定的列执行?

如果我有一列包含大量数据的真正减慢查询,哪能有我的对象排除了该列从生成的SQL?

如果我的表中有ID(INT),姓名(INT),数据(BLOB),我怎样才能使我的查询是

  SELECT标识,从表名名称
 

而不是

 选择编号,名称,从表名数据
 

从下面的建议下,我的方法是

 公开名单< T> GetBy< T>(的DbContext的背景下,前pression< Func键< T,布尔>>精通,防爆pression< Func键< T,T>>列)其中T:类
    {

        返回dbContext.Set< T>(),其中(EXP)。选择< T,T>(列).ToList();
    }
 

和我打电话,象这样

 名单,其中,CampaignWorkType>名单= GetBy< CampaignWorkType>(的DbContext,C => c.Active == true,则N =>新建{n.Id,n.Name});
 

我得到了一个错误,如下面的。

无法隐式转换类型'AnonymousType#1到Domain.Campaign.CampaignWorkType

我怎么能解决这个问题?

解决方案

解决的办法是:

首先,定义一个代理类型:

 公共类CampaignWorkTypesSimpleList
{
   公众诠释编号{获得;组; }
   公共字符串名称{;组; }
}
 

然后改变通用的方法是这样的:

 公开名单< U> GetBy< T,U>(的DbContext的背景下,前pression< Func键< T,布尔>>精通,防爆pression< Func键< T,U>>列)
                其中T:类
                其中U:类
{

  返回dbContext.Set< T>(),其中(EXP)。选择< T,U>(列).ToList();
}
 

最后,执行它。

 名单,其中,CampaignWorkTypesSimpleList>名单= this.GetBy< CampaignWorkType,CampaignWorkTypesSimpleList>(的DbContext,C => c.Active == true,则N =>新建CampaignWorkTypesSimpleList {n = n.Id,名称= n.Name});
 

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 });

这篇关于如何检索实体框架特定的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆