在Linq查询中使用C#中的DateTime值从Database分配/比较DateTime值

时间:2012-08-28 04:02:35

标签: asp.net-mvc-3 linq c#-4.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();

2 个答案:

答案 0 :(得分: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的查询正在返回Top10Date的实例,该实例无法自动转换为DateTime?。您可以使用linq方法Select()让您的查询返回不同的内容 - 在这种情况下Date中的Top10Date属性

答案 1 :(得分: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());
            }

此处还有如何获取latestDate的DateId:

    int dateId = topDate.Where(d => d.Date == latestDate).Select(x => x.DateId).FirstOrDefault();