使用 linq 选择特定列:传输了什么? [英] Selecting specific columns using linq: What gets transferred?

查看:19
本文介绍了使用 linq 选择特定列:传输了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我参考这个例子:返回选定的指定列

引用:如果 BlobDetails 不是 LINQ 实体,那么您可以直接执行:

Quote: If BlobDetails isn't the LINQ entity, then you can do it directly:

var qry = from b in dc.Blobs
          orderby b.RowVersion descending
          select new BlobDetails {
              Id = b.Id, Size = b.Size,
              Signature = b.Signature, RowVersion = b.RowVersion};

return qry.ToList();

我看到他们通过 ORM 工具 LINQ TO SQL 在查询中选择特定列.ORM 工具的批评者说,如果我没记错的话,ORM 工具从表中选择并返回整个对象,并限制了仅选择特定列的选项,就像通过经典 SQL 编程可以做到的那样.当然,当我看到这个例子时,我对此表示怀疑,但尽管如此,我仍然不断问自己这个问题:数据库是只返回选定的列,还是返回整个对象,将列过滤留给ORM-工具?

I see that they are selecting specific column in a query through the ORM-tool LINQ TO SQL. Critics of ORM-tools say that, if I remember correctly, that ORM-tools select and return entire objects from the table, and limits the options of selecting only specific columns as one can do through classic SQL-programming. Of course, I have my doubts about that when I see this example, but nevertheless, I still keep asking myself the question: Does the database return only the selected columns, or does it return the entire objects, leaving the column-filtering to the ORM-tool?

在这个例子中,他们还有一个叫做 Blobdetails 的类:

From this example, they also have a class called Blobdetails:

public class BlobDetails   
{  
    public int Id { get; set; }  
    public string Signature { get; set; }  
    public int Size { get; set; }  
    public System.Data.Linq.Binary RowVersion { get; set; }     
}

每次我只想通过 LINQ 从表中选择几列时,是否都需要创建自己的类?

Do I need to create my own classes everytime I only wish to select a few columns from a table through LINQ?

推荐答案

您无需创建新类即可从表中选择几列.您可以为此使用匿名类型.

You don't need to create new classes to select few columns from a table. You can use anonymous types for that.

var qry = from b in dc.Blobs
          orderby b.RowVersion descending
          select new { b.Id, b.Size, b.Signature, b.RowVersion};

return qry.ToList();

仅传输选定的列.使用普通 SQL 和使用 LINQ to SQL 没有区别.当您执行 LINQ 查询时,它会转换为纯 SQL 并执行.然后将结果映射到您的对象.

Only selected columns are transferred. There is no difference between using plain SQL and using LINQ to SQL. When you are executing LINQ query, it is converted to plain SQL and executed. Then result is mapped to your objects.

您可以使用 SQL Server Profiler 查看在服务器上生成和执行的查询.您也可以使用 LINQPad 来查看将从您的查询中生成的 SQL.在您的情况下,无论您使用 BlobDetails 还是匿名对象,查询都将相同:

You can use SQL Server Profiler to see what query was generated and executed on server. Also you can use LINQPad to see what SQL will be generated from your query. In your case query will be same either you use BlobDetails or anonymous object:

SELECT [t0].[Id], [t0].[Size], [t0].[Signature], [t0].[RowVersion]
FROM [Blobs] AS [t0]
ORDER BY [t0].[RowVersion] DESC

这篇关于使用 linq 选择特定列:传输了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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