无法从DateTime中减去

时间:2016-03-05 06:06:29

标签: c# asp.net-mvc linq

我有数据库,我有TimeStartTimeEnd,所以我想只获得StudentName个值,他们需要30天才能完成。因此,每个StudentName都有TimeStartTimeEnd

视图模型:

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

型号:

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

正如您所看到的,我创建了一个SelectList项来创建新的TimeStartTimeEnd,这是我的逻辑:

创建获取:

public ActionResult Create()
{
   var vm = new StudentViewModel
        {
            DurationDays = new List<SelectListItem>()
            {
                new SelectListItem {Value = "1", Text = "1 year"},
                new SelectListItem {Value = "2", Text = "2 years"},
            }};
   return View(vm);
}

创建帖子

public async Task<ActionResult> Create([Bind(Include = "TimeStart,TimeEnd,StudentName,SelectedDurationDays")] StudentsViewModel model)
{
    var endDate = DateTime.Now.AddYears(model.SelectedDurationDays);
    var students = new Students

    try
    {
        if (ModelState.IsValid)
        {
            StudentName = model.StudentName,
            TimeStart = DateTime.Now,
            TimeEnd = endDate
        };

        db.WebPagesList.Add(students);
        db.SaveChanges();

        return RedirectToAction("Index", "Student");
    }
    catch (Exception)
    {
        //exception Return
    }
}

索引获取:

public async Task<ActionResult> Index(WebPages model)
{
        var datesub = model.DomainExp.AddDays(-30);

        var datetimened = db.StudentList.Where(x => x.StudentName== model.StudentNAme
               && x.TimeEnd<= datesub);
        var StudentList = db.StudentList.Include(w => w.Student);
        return View(await StudentList.ToListAsync());
}

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

var datesub = model.TimeEnd.AddDays(-30);
var datetimened = db.MyModelList.Where(x => x.StudentName ==    model.StudentName && x.TimeEnd<= datesub);

但是我收到了一个错误:

  

添加或减去的值会导致无法表示的DateTime。

在这一行:

var datesub = model.TimeEnd.AddDays(-30);

我的查询错误了什么?我只想选择靠近StudentName

TimeEnd

修改

作为@Stephen Muecke的评论,我需要在GET方法中设置TimeEnd,如果我在帖子之前没有TimeEnd我怎么能这样做(我发帖时创建它)新学生?)

2 个答案:

答案 0 :(得分:2)

如果model.TimeEnd是默认的未初始化DateTime.MinValue1/1/0001 12:00:00 AM),那么尝试从中减去30天将无效。在尝试从中删除之前,请确保已使用实际日期时填充此属性。

我认为当您将值提交回Post操作时,这个值根本就没有填充。

答案 1 :(得分:1)

已提及Darin Dimitrov,您将在无效点减去。

相反,您应添加 30天到今天的日期,因为您要查询那些在此时间范围内已过期的记录。

var datediff = DateTime.Now.AddDays(30);
var studentsAboutToExpire = db.MyModelList
   .Where(x => x.StudentName == model.StudentName && x.TimeEnd<= datediff);