0

How to check if a value already exists in database

I would like to check if notificationStartDate and notificationEndDate already exist in the database. So I don't create 2 fields with the same notificationStart Date and notificationEndDate.

public ActionResult Create(
    [Bind(Include = "notificationID,notificationName,notificationText,
    notificationStartDate,notificationEndDate,notificationEnabledDisabled")] 
    tbl_notification tbl_notification)
{
    if (ModelState.IsValid)
    {
        db.tbl_notification.Add(tbl_notification);

        db.SaveChanges();
        return RedirectToAction("Index");           
    }
    return View(tbl_notification);
}
Mohammed Noureldin
  • 14,913
  • 17
  • 70
  • 99

1 Answers1

0

You can use Any to check whether such an entry already exists in the database:

public ActionResult Create([Bind(Include = "notificationID,notificationName,notificationText,notificationStartDate,notificationEndDate,notificationEnabledDisabled")] tbl_notification tbl_notification)
{
    if (ModelState.IsValid)
    {
        if(!db.tbl_notification.Any(x => x.notificationStartDate == tbl_notification.notificationStartDate  &&
                                         x.notificationEndDate == tbl_notification.notificationEndDate)
        {
             db.tbl_notification.Add(tbl_notification);
             db.SaveChanges();
        }
        return RedirectToAction("Index");           
    }
    return View(tbl_notification);
}
SomeBody
  • 7,515
  • 2
  • 17
  • 33
  • How can I keep the values without refreshing the page and just show already exists instead of inputting all the values again? – Brandon Mifsud Aug 05 '21 at 07:26