如何使用linq查询日期时间?

时间:2016-03-04 17:35:06

标签: c# asp.net-mvc linq

我有数据库,我有TimeStartTimeEnd,所以我想只获得StudentName个值,然后才能完成。因此,每个StudentName都有TimeStartTimeEnd

视图模型:

    public List<SelectListItem> DurationDays { set; get; }
    public int SelectedDurationDays { set; get; }

型号:

 [Key]
    public int MyModelId { get; set; }
    public String StudentName { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime TimeStart{ get; set; }

    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public DateTime TimeEnd{ get; set; }

正如你所看到的,我做一个SelectList项来创建一个新的TimeStart和TimeEnd,有我的逻辑:

创建获取:

  public async Task<ActionResult> Index(StudentsViewModel model)
    {
   var vm = new myViewModel
        {
            DurationDays = new List<SelectListItem>()

            {
                new SelectListItem {Value = "1", Text = "1 year"},
                new SelectListItem {Value = "2", Text = "2 years"},
            }}

创建帖子

 var endDate = DateTime.Now.AddYears(model.SelectedDurationDays);

所以我尝试检查即将结束的值是:

     var studentsEnd = db.MyModelList.Where(x => x.StudentName == model.StudentName)
            .Select(x => x.TimeEnd <= 10);
         if (studentsEnd <= 10)
        {
            //Alert logic
        }

我的查询出错了什么?我只想选择TimeEnd附近的StudentName

1 个答案:

答案 0 :(得分:2)

Your LINQ is wrong because you aren't doing any where clause using DateTime.

In your current LINQ, it could be translated to something like this in SQL:

SELECT (timeEnd <= 10) FROM MyModelList WHERE StudentName = ~variable~

You should've put the DateTime condition inside your .Where() clause too, like this:

 var studentsEnd = db.MyModelList.Where(x => x.StudentName == model.StudentName 
                   && x.TimeEnd <= otherDate);

Also, you're comparing a DateTime with a int value, it doesn't make any sense. You can only compare DateTimes with DateTimes.

If you're new to LINQ syntax querying a database, I do recommend you to use LINQPad.