简体   繁体   English

使用max进行实体框架查询

[英]Entity Framework querying with max

Someone asks me to convert the T-SQL statement into LINQ to EF query: 有人要求我将T-SQL语句转换为LINQ to EF查询:

SELECT * FROM  CopperPrices  
where ID in 
  (select max(ID) as ID from copperprices group by market, pname)

I use common LINQ-TO-OBJECT ideas and give the following answer: 我使用常见的LINQ-TO-OBJECT想法,并给出以下答案:

class CopperPrice
{
    public int ID { get; set; }
    public string Market { get; set; }
    public string PName { get; set; }
}

var result = from p in copperPrices
      group p by new { Market = p.Market, PName = p.PName } into g
      select g.OrderByDescending(p => p.ID).First();

But it's not working in EF because of the following exception: 但是由于以下异常,它在EF中不起作用:

The method 'First' can only be used as a final query operation. 方法“ First”只能用作最终查询操作。 Consider using the method 'FirstOrDefault' in this instance instead 考虑在此实例中使用方法“ FirstOrDefault”

Can the above T-SQL statement be converted to one LINQ query statement? 可以将上面的T-SQL语句转换为一个LINQ查询语句吗?

Here you go: 干得好:

var result1 = copperPrices.GroupBy(g => new { g.Market, g.PName }).Select
     (
         x => x.ToList().OrderByDescending(z => z.ID).FirstOrDefault()
     );

The important part here is the .Select(x => x.ToList()). 这里的重要部分是.Select(x => x.ToList())。 The ToList returns the values of an IGrouping, each of which is what you ultimately want to order and select the max of. ToList返回IGrouping的值,每个值都是您最终要订购的值并选择最大值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM