如何在LINQ中完成这个SQL?

时间:2011-04-12 11:03:42

标签: linq linq-to-entities

我有这个简单的SQL查询...

-- BestSeller
SELECT TOP(1) v.make, v.model, COUNT(v.make) AS NoSold
FROM Vehicles v
group by v.make, v.model
order by NoSold DESC

我使用实体框架,并希望使用linq做同样的事情。到目前为止我有......

                var tester = (from v in DB.VP_Historical_Vehicles
                         group v by v.make into g
                         orderby g.Count() descending
                         select new { make = g.Key, model = g, count = g.Count() }).Take(1);

            foreach(var t in tester)
            {
                BestSeller.Make = t.make;
                BestSeller.Model = t.make;
                BestSeller.CountValue = t.count;
            }     

我不断超时,数据库很大但SQL运行速度很快

任何sugestions?

感谢

truegilly

3 个答案:

答案 0 :(得分:2)

按复合键分组。

var t = (
    from v in DB.VP_Historical_Vehicles
    group v by new { v.make, v.model } into g
    orderby g.Count() descending
    select new { make = g.Key.make, model = g.Key.model, count = g.Count() }
    )
    .First();

BestSeller.Make = t.make;
BestSeller.Model = t.make;
BestSeller.CountValue = t.count;

答案 1 :(得分:0)

检查使用LINQ运行它时执行的查询。

我怀疑你orderby g.Count() descending可能正在为每一行执行COUNT查询,这至少会对性能造成影响。

使用EF时,请始终检查LINQ语句在查询方面产生的内容。创建导致n+1 scenario的查询非常容易。

答案 2 :(得分:0)

感谢Scott Weinstein回答我能够让它运作

如果有更有效的方法,请评论...

        VehicleStatsObject BestSeller = new VehicleStatsObject();

        using (var DB = DataContext.Get_DataContext)
        {
            var t = (from v in DB.VP_Historical_Vehicles
                     group v by new { v.make, v.model } into g
                     orderby g.Count() ascending
                     select new { make = g.Key.make, model = g.Key.model, count = g.Count() }).OrderByDescending(x => x.count).First();

                BestSeller.Make = t.make;
                BestSeller.Model = t.model;
                BestSeller.CountValue = t.count;                              
        }

        return BestSeller;