0

我有以下课程:

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();
4

2 回答 2

1

尝试

if (!latestDate.HasValue)
    latestDate = (DateTime?)(topDate.OrderByDescending(d => d.Date).Select( x => x.Date).FirstOrDefault());    

if (date == "PreviousDate")
{
    latestDate = (DateTime?)(topDate.Where(d => d.Date < latestDate.Date).OrderByDescending(d => d.Date).Select(x => x.Date).FirstOrDefault());
}

if (date == "NextDate")
{
    latestDate = (DateTime?)(topDate.Where(d => d.Date > latestDate.Date).OrderBy(d => d.Date).Select(x => x.Date).FirstOrDefault());
}

您的查询正在返回一个无法自动转换为topDate的实例。您可以使用 linq 方法让您的查询返回不同的东西 - 在这种情况下,属性Top10DateDateTime?Select()DateTop10Date

于 2012-08-28T04:42:21.293 回答
0

如果其他人遇到类似问题,这是工作代码。我花了一整天的时间才弄清楚这一点。我非常感谢 StanK 向我展示了正确的道路:

if (!latestDate.HasValue)
            {
                latestDate = (DateTime?)(topDate.OrderByDescending(d => d.Date).Select(x => x.Date).FirstOrDefault());
            }


           if ( date == "PreviousDate")
            {
                latestDate = (DateTime?)(topDate.Where(d => d.Date < latestDate).OrderByDescending(d => d.Date).Select(x => x.Date).FirstOrDefault());                
            }

            if (date == "NextDate")
            {
                latestDate = (DateTime?)(topDate.Where(d => d.Date > latestDate).OrderBy(d => d.Date).Select(x => x.Date).FirstOrDefault());
            }

这里还有如何获取最新日期的 DateId:

    int dateId = topDate.Where(d => d.Date == latestDate).Select(x => x.DateId).FirstOrDefault();
于 2012-08-28T05:26:22.667 回答