我有以下课程:
public class Top10Date
{
[Key]
public int DateId { get; set; }
public DateTime Date { get; set; }
}
与数据库中的 Top10Date 表相关联。我正在尝试进行比较并将值分配给控制器类中的 latestDate:
public ActionResult Index(string date, DateTime? latestDate)
{
var topDate = db.Top10Dates;
if (!latestDate.HasValue)
latestDate = (DateTime?)(topDate.OrderByDescending(d => d.Date).FirstOrDefault());
if (date.Value == "PreviousDate")
{
latestDate = (DateTime?)(topDate.Where(d => d.Date < latestDate.Date).OrderByDescending(d => d.Date).FirstOrDefault());
}
if (date.Value == "NextDate")
{
latestDate = (DateTime?)(topDate.Where(d => d.Date > latestDate.Date).OrderBy(d => d.Date).FirstOrDefault());
}
....
ViewBag.latestDate = latestDate
return View();
}
但它给了我各种各样的错误。我也尝试过其他的东西,但没有一个有效:
latestDate = topDate.OrderByDescending(d => d.Date).FirstOrDefault();
latestDate.Value = topDate.OrderByDescending(d => d.Date).FirstOrDefault();
latestDate = topDate.Where(d => d.Date > latestDate.Value.Date).OrderBy(d => d.Date).FirstOrDefault();
另外我如何从数据库中获取 DateId?我试过了,现在可以了。
var dateId = (DateTime?)top10Date.Where(d => d.Date == latestDate.Value.Date).Select(x => x.DateId).FirstOrDefault();