【问题标题】:Linq behind the scenes林克幕后
【发布时间】:2010-12-09 12:06:21
【问题描述】:

非常感谢您详细解释(以及是否)在这些情况下,以下 Linq to Entities 相关代码 sn-p 的幕后情况有所不同:
A. "foreach" 循环在 "using" 子句中
B. 我使用的是在 Linq to Sql 上运行查询的类似映射,而不是 Linq to Entites。
C. A+B。

代码:

 ILookup<string, tblProduct> productBooks;
        using (TbsDBEntities tbsDbEntities = new TbsDBEntities())
        {
            productBooks = (from tbsDbEntity in tbsDbEntities.tblProducts
                            orderby tbsDbEntity.Title
                            select tbsDbEntity).ToLookup(p => p.Title.Substring(0, 1).ToUpper());

        }


        foreach (IGrouping<string, tblProduct> productBook in productBooks)
        {
            if (productBook.Key[0] >= 'A' && productBook.Key[0] <= 'Z')
            {
                HtmlAnchor anchor = new HtmlAnchor();
                anchor.InnerText = productBook.Key+"    ";
                anchor.HRef ="/"+ productBook.Key;
                divHeader.Controls.Add(anchor);
            }

【问题讨论】:

    标签: c# .net linq linq-to-sql linq-to-entities


    【解决方案1】:

    using 关闭后,我仔细查看了这个并认为“这行不通”。

    但是ToLookup() 实际上执行了 SQL 语句,所以这一切都很好。将其保留为 IEnumerable 将导致它在您的第二次 foreach 中失败,因为上下文将被处理。 Linq to SQL 可以使用此代码。

    【讨论】:

      【解决方案2】:

      幕后: 该代码通过实体映射访问产品的数据库列表。通常人们会为 ADO.NET 实体框架 + Linq 编写此代码到实体。

      代码使用 linq 来提取数据行,而不是使用典型的 sql 查询,例如“从产品中选择 *”。实体映射预计会在幕后生成查询并获取数据。如果您有 sql profiler 之类的工具您将能够看到代码传递给 sql server 的查询。

      foreach 通常为从 linq 语句返回的每个产品创建链接......并将链接添加到 .. 中。if 语句可能会保护代码免受不以字母字符开头的产品名称的影响......所以可能检查 >= A 和


      A.应该没有区别。

      B.如果 tblProducts 有大量数据,您可能会获得相当大的性能提升。因为 linq-to-database 将有助于避免为所有数据构建实体对象。

      C.与 B 相同...因为我相信在“使用”中包含 for 循环并不会使其有任何不同

      【讨论】:

      • 你能详细说明B吗?
      • Linq-to-Entities 在查询数据库之前为数据库创建一个实体模型,就像在幕后拥有一个带有实体的 DataLayer.. 数据实体将数据库结果加载到对象实体,并且linq-to-entities 在对象实体上工作以生成 IEnumerable(Element) object .. linq 查询的结果。 Linq-to-SQL 直接查询数据库并为结果加载一个 IEnumerable(Element) 对象......这消除了创建实体的开销。
      猜你喜欢
      • 2010-10-16
      • 2011-10-13
      • 1970-01-01
      • 2023-01-03
      • 2020-12-06
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      相关资源
      最近更新 更多