【问题标题】:Find the last record based on date根据日期查找最后一条记录
【发布时间】:2016-05-04 01:08:40
【问题描述】:

在我的控制器中,特别是 Create 操作。我希望其中一个文本框自动填充基于日期的最新记录中的值。

例如,如果我的汽车在 2016 年 5 月 2 日行驶里程为 26.3.. 那么当我想为 5/3/2016 创建记录时,文本框应为 autopopulated 和 26.3。

这是我所拥有的:

public ActionResult Create(int? id)
{
    MaintenanceRecord newMaintenanceRecord = new MaintenanceRecord();

    decimal oldMaintenanceRecord = db.MaintenanceRecords.Single(x => x.AircraftID == id && x.DateEntered == DateTime.Today.AddDays(-1)).AirFrame;

    newMaintenanceRecord.DateEntered = DateTime.Today.Date;
    newMaintenanceRecord.AirFrame = oldMaintenanceRecord;


    ViewBag.AID = new SelectList(db.AInfoes, "ID", "RegNum");
    return View(newMaintenanceRecord);
}

但是当我转到 Create 页面时,我收到:

LINQ to Entities 无法识别方法“System.DateTime AddDays(Double)”方法,并且该方法无法转换为存储表达式。

那么我需要修改什么来根据日期检索数据库中最新的Airframe

感谢任何帮助。

【问题讨论】:

    标签: c# linq asp.net-mvc-5


    【解决方案1】:

    你可以像下面这样使用:

    DateTime yesterday=DateTime.Today.AddDays(-1);
    decimal oldMaintenanceRecord = db.MaintenanceRecords
                                   .Single(x => x.AircraftID == id && 
                                   x.DateEntered == yesterday)
                                   .AirFrame;
    

    【讨论】:

      【解决方案2】:

      更重要的是,为什么您认为最近的时间正好是一天? “最新”只是 DateTime 列中价值最高的那个,不是吗?

      因此只需按该值降序排列并获取第一条记录。像这样的:

      decimal oldMaintenanceRecord = db.MaintenanceRecords
          .Where(x => x.AircraftID == id)
          .OrderByDescending(x => x.DateEntered)
          .First().AirFrame;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-14
        • 2018-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-30
        • 1970-01-01
        相关资源
        最近更新 更多