我正在 ASP.NET MVC C# 中制作一个 Web Scheduler。因此,我在 Controller 中创建了 Create ActionResult,如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,NomeResponsavelEvento,NomeEvento,DataInicioEvento,HorarioInicioEvento,DataFinalEvento,HorarioFinalEvento")] Evento evento)
{
var teste = from x in db.Eventos where x.HorarioInicioEvento.Hour.Equals(evento.HorarioInicioEvento.Hour) select x;
if (ModelState.IsValid)
{
db.Eventos.Add(evento);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
TempData["ErroHorarioExistente"] = "Já possui um evento no horário informado! Tente outro horário.";
return RedirectToAction("Index");
}
return View(evento);
}
我想要做的是检查(可能使用 if 语句)数据库中是否在新创建表单事件的同一小时:分钟内已经有一个事件。我在“var teste”中使用了一些断点,但它总是显示 null,即使数据库中已经有一个与我的表单具有相同日期时间的事件。当我尝试在这个问题中做另一个例子时:How to check if a record already exists in the db using asp.Net MVC
我可以让它工作为: db.Eventos.Any(ag => ag.DataInicioEvento == evento.DataInicioEvento) 但此方法仅检查某个日期是否相等,然后返回 true 已经有一个相同的日期日期并且有效。但我需要它工作一小时:分钟
最佳答案
首先,您应该将制动点放在 var teste = ...
之后,因为断点在执行行之前停止。接下来,如果您想要相同的小时和分钟,您可以这样做:
var teste = db.Eventos.Where(ag =>
ag.DataInicioEvento.Hour == evento.DataInicioEvento.Hour
&& ag.DataInicioEvento.Minute == evento.DataInicioEvento.Minute
)
关于c# - 检查数据库是否已经有一个日期时间等于表单中传递的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38102502/