如何防止用户在同一日期预约时间在c#?

时间:2015-03-24 13:47:04

标签: c# sql asp.net asp.net-mvc visual-studio

我可以在if语句中添加什么来比较时间,所以一旦日期相同,它会继续检查时间并让用户知道时间是否已经预订?

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Appointment appointment)
{
    try
    {
       string UserName = User.Identity.Name;
       appointment.username = UserName;

       DateTime date1 = appointment.AppointmentDateTime.Date;

       IEnumerable<Appointment> ApntDate = db.Appointment.ToList().Where(q=> q.AppointmentDateTime.Date == date1);                   

       if (ApntDate != null)
       {
            DateTime time = System.DateTime.Now;
            for (int i = 0; i < ApntDate.Count(); i++)
            {
                 if (date1 == ApntDate.ElementAt(i).AppointmentDateTime)
                 {

                 }
            }
        }

        db.Appointment.Add(appointment);
        db.SaveChanges();

        return RedirectToAction("Index", "Appointment");       
    }
    catch (Exception ex)
    {
      return View(ex.ToString());
    }
 }

1 个答案:

答案 0 :(得分:4)

您应该使用FirstOrDefault,如下所示

   DateTime date1 = appointment.AppointmentDateTime.Date;


   var ApntDate = 
           db.Appointment
           .FirstOrDefault(q=>q.AppointmentDateTime.Date == date1);                   

     if(ApntDate!=null){//book new}
     else{return Content("You have already booked!");}