2

我有以下 SQL 查询...

    select  seaMake AS Make,
        seaModel AS Model,
        COUNT(*) AS [Count],
        MIN(seaPrice) AS [From],
        MIN(seaCapId) AS [CapId]
from tblSearch 
where seaPrice >= 2000
and seaPrice <= 7000
group by seaMake, seaModel
order by seaMake, seaModel

我试图将其编写为 LINQ to Entities 查询,但我遇到了问题。这是我到目前为止所拥有的,但我无法从 var S 访问品牌和型号值

var tester = from s in db.tblSearches
             where s.seaPrice >= 2000
             && s.seaPrice <= 7000
             orderby s.seaMake
             group s by s.seaMake into g
             select new
             {
                 make = g.seaMake,
                 model = s.seaModel,
                 count = g.Max(x => x.seaMake),
                 PriceFrom = g.Min(s.seaPrice)
              };

我哪里错了?

4

2 回答 2

2

这应该是 SQL 的直接翻译:

from s in db.tblSearches
where
    s.seaPrice >= 2000 &&
    s.seaPrice <= 7000
group s by new {s.seaMake, s.seaModel} into g
orderby g.Key
select new
{
    Make =  g.Key.seaMake,
    Model = g.Key.seaModel,
    Count = g.Count(),
    From =  g.Min(x => x.seaPrice),
    CapId = g.Min(x => x.seaCapId)
}
于 2012-10-17T19:40:49.167 回答
1

IEnumerable<TypeOfS>当您分组到g 时,您将该集合转换为 IEnumerable>而不是您的原始集合,因此当前范围内的集合是g. 所以以下是有效的

from s in db.tblSearches
where s.seaPrice >= 2000
   && s.seaPrice <= 7000
orderby s.seaMake
group s by s.seaMake into g // the collection is now IEnumerable<IGrouping<TypeOfSeaMake, TypeofS>>
select new {
    make = g.Key, // this was populated by s.seaMake
    model = g.First().seaModel, // get the first item in the collection
    count = g.Max(x => x.seaMake), // get the max value from the collection
    PriceFrom = g.Min(x => x.seaPrice), // get the min price from the collection
};

现在将为每个分组返回一个项目

于 2012-10-17T19:47:24.560 回答