【问题标题】:Is it inefficient that linq to sql translates this query into the format: "select *"?linq to sql 将此查询转换为格式:“select *”是否效率低下?
【发布时间】:2023-03-21 22:05:02
【问题描述】:

我对 Linq to SQL 还不是很熟悉,但让我印象深刻的是:

var articles = 
  (from a in DB.Articles
  where 
  a.ArticleId == ArticleId.Question &&
  a.DeletedAt == null &&
  a.Votes >= minVotes
  orderby a.UpdatedAt descending
  select a).
  Take(maxarticles);

翻译成这样:

string query = 
  "select top 10 * from articles
  where 
  ArticleId = 1 and 
  DeletedAt is null and 
  Votes >= -5
  order by UpdatedAt desc";

linq to sql 愿意使用“select *”类型的查询来清理所有内容,这让我感到效率低下。 这不是低效吗?

为什么 linq to sql 会这样呢?

【问题讨论】:

    标签: .net sql database performance linq-to-sql


    【解决方案1】:

    如果您想选择更少的列,则必须在 linq 查询中使用投影。

    var articles = (from a in DB.Articles
        where a.ArticleId == ArticleId.Question 
            && a.DeletedAt == null 
            && a.Votes >= minVotes
        orderby a.UpdatedAt descending
        select new 
        {
           a.ArticleId,
           a.Votes
        })
        .Take(maxarticles);
    

    执行上述操作将转换为如下所示的 SQL...

    select top 10 
             ArticleId,
             Votes
    from     articles
    where    ArticleId = 1 
             and DeletedAt is null
             and Votes >= -5
    order by UpdatedAt desc
    

    【讨论】:

      【解决方案2】:

      不使用“SELECT *”背后的想法是避免带来不必要的列。

      在您的情况下,当您指定“选择一个”时,您特别要求 linq to sql 带来所有列

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-11
        • 2019-12-12
        • 2017-10-06
        • 2020-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多