只得到具体的列 [英] Only get specific columns

查看:140
本文介绍了只得到具体的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以让我的EF对象只检索执行的sql中的特定列吗?如果我正在执行以下代码来检索对象,有没有什么可以做的,只有在需要时才能获得某些列?

Can I make my EF objects retrieve only specific columns in the sql executed? If I am executing the below code to retrieve objects, is there something I can do to only get certain columns if wanted?

public IEnumerable<T> GetBy(Expression<Func<T, bool>> exp)
{
    return _ctx.CreateQuery<T>(typeof(T).Name).Where<T>(exp);
}

这将生成一个包含所有列的select子句。但是,如果我有一个列包含大量的数据真的会减慢查询速度,那么我怎么能让我的对象从sql生成的列中排除该列?

This would generate a select clause that contains all columns. But, 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?

如果我的表有Id(int),Status(int),Data(blob),我如何使我的查询是

If my table has Id(int), Status(int), Data(blob), how can I make my query be

select Id, Status from TableName

而不是

select Id, Status, Data from TableName

从我的方法是

public IEnumerable<T> GetBy(Expression<Func<T, bool>> exp, Expression<Func<T, T>> columns)
{
    return Table.Where<T>(exp).Select<T, T>(columns);
}

我打电话就这样

mgr.GetBy(f => f.Id < 10000, n => new {n.Id, n.Status});

但是,我收到一个编译错误:

However, I'm getting a compile error:


不能将类型AnonymousType#1隐式转换为Entities.BatchRequest

Cannot implicitly convert type 'AnonymousType#1' to 'Entities.BatchRequest'


推荐答案

当然可以。这样做:

var q = from r in Context.TableName
        select new 
        {
            Id = r.Id,
            Status = r.Status
        }

这是一个实际的例子(显然,我的数据库有不同的表比你的)。我将我的EF模型添加到LINQPad,并键入以下查询:

Here's an actual example (obviously, my DB has different tables than yours). I added my EF model to LINQPad and typed the following query:

from at in AddressTypes
select new
{
    Id = at.Id,
    Code = at.Code
}

LINQPad向我显示生成的SQL是:

LINQPad shows me that the generated SQL is:

SELECT 
    1 AS [C1], 
    [Extent1].[AddressTypeId] AS [AddressTypeId], 
    [Extent1].[Code] AS [Code]
FROM 
    [dbo].[AddressType] AS [Extent1]

表中没有其他字段。

响应更新的问题

您的参数表示需要一个类型T并返回相同的类型。因此,您传递的表达式必须符合此要求,或者您需要更改参数的类型,即:

Your columns argument says it takes a type T and returns the same type. Therefore, the expression you pass must conform to this, or you need to change the type of the argument, i.e.:

public IEnumerable<U> GetBy<U>(Expression<Func<T, bool>> exp, Expression<Func<T, U>> columns)
{
    return Table.Where<T>(exp).Select<T, U>(columns);
}

现在表达式可以返回您要使用的任何类型。

Now the expression can return any type you care to use.

这篇关于只得到具体的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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