【问题标题】:How to check if a values already exists in database [duplicate]如何检查数据库中是否已存在值[重复]
【发布时间】:2021-10-10 04:28:38
【问题描述】:

如何检查一个值是否已经存在于数据库中

我想检查数据库中是否已经存在 notificationStartDate 和 notificationEndDate。所以我不会创建 2 个具有相同 notificationStart Date 和 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);
}

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您可以使用Any检查数据库中是否已经存在这样的条目:

    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);
    }
    

    【讨论】:

    • 如何在不刷新页面的情况下保留值,只显示已经存在而不是再次输入所有值?
    猜你喜欢
    • 2011-12-22
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2017-11-24
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多