【问题标题】:How do I get the most recent entry from a table using LINQ?如何使用 LINQ 从表中获取最新条目?
【发布时间】:2014-02-04 15:07:11
【问题描述】:

我有一张价格表,其中有一列更新日期。每次价格发生变化时,都会在表格中创建一个新条目。

为了返回最新价格,我尝试按日期排序,然后使用 .Last() 获取最新条目:

 var upgrades = from d in vf.tl_phn_devices
                       where d.available == true
                       select new
                       {
                           DeviceName = d.tl_phn_manufacturer.manufacturer + " " + d.model,
                           Price = (from p in vf.tl_phn_prices 
                                    where p.deviceID == d.deviceID
                                    orderby p.dateUpdated ascending
                                    select p.price).Last(),
                           URL = d.url,
                           ImageURL = d.image

                       };

但是,当我运行上述程序时,我收到一条错误消息,指出 .Last() 不受支持。 我也试过 .AsEnumberable().Last() 但这也没有用。

在代码的其他地方,我通过采取额外的步骤解决了类似的问题:

  var orders = (from o in vf.tl_phn_orders
                    where o.login == CurrentUserName
                    orderby o.date ascending
                    select new
                     {
                         Login = o.login,
                         Name = o.name,
                         Device = o.tl_phn_device.tl_phn_manufacturer.manufacturer + " " + o.tl_phn_device.model,
                         Price = o.tl_phn_price.price,
                         date = o.date

                     }).AsEnumerable();

        var order = orders.LastOrDefault();

但我想一次性完成所有操作,这样我就可以在第一个查询中返回它。

【问题讨论】:

    标签: c# sql linq


    【解决方案1】:

    只需执行orderby descending,然后选择First

    LastLastOrDefault 是带有实体框架的 not supported,因为它们不能被翻译成底层语言(你的情况是 SQL)

    orderby p.dateUpdated descending
    select p.price).First(),
    

    您可能还会看到:Supported and Unsupported LINQ Methods (LINQ to Entities)

    【讨论】:

    • 链接页面没有水平滚动条还是只是我的浏览器
    • @ElectricRouge,它是一个 MSDN 页面,不需要在我的屏幕上水平滚动
    • @ElectricRouge,刚刚在第二个屏幕上试过,是的,你必须选择并向右滚动,奇怪。 MSDN 男人!!
    【解决方案2】:

    使用First() 并更改顺序:

     var upgrades = from d in vf.tl_phn_devices
                    where d.available
                    select new
                    {
                        DeviceName = d.tl_phn_manufacturer.manufacturer + " " + d.model,
                        Price = (from p in vf.tl_phn_prices 
                                 where p.deviceID == d.deviceID
                                 orderby p.dateUpdated descending
                                 select p.price).First(),
                        URL = d.url,
                        ImageURL = d.image    
                    };
    

    问题是 EntityFramework 无法为您的查询生成 SQL。

    您的第二个查询使用 .Last() 有效,因为您已将实体加载到内存中(使用 .AsEnumerable())并且现在使用 LINQ to Objects 而不是 LINQ to Entities。

    由于嵌套查询,您不能对第一个查询执行相同操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多