防止用户将重复的数据发布到数据库中

本文关键字:数据库 数据 用户 | 更新日期: 2023-09-27 17:50:00

我想在Asp.net MVC项目中实现对创建重复数据的限制。

我有一个表tSectionForwardSelling (SectionForwardSellingID, StoreID, SectionID, Amount, Date)。

我想限制用户输入重复的数据,如果他想在tSectionForwardSelling中输入的数据已经具有相同的StoreID和SectionID。如果存在具有相同StoreID和SectionID的数据,他只能编辑。

我想避免这个:

    Amount    Date       SectionName     StoreName 
    $1000   5/20/2015        Men          Clarissa 
    $2345   5/20/2015        Men          Clarissa

这是我的创建ActionResult从tSectionForwardSellings控制器:

// GET: tSectionForwardSellings/Create
public ActionResult Create()
{
    ViewBag.SectionID = new SelectList(db.tSections, "SectionID", "Section_Name");
    ViewBag.StoreID = new SelectList(db.tStores, "StoreID", "Store_Name");
    return View();
}
// POST: tSectionForwardSellings/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SectionForwardSellingID,Amount,Date,StoreID,SectionID")] tSectionForwardSelling tSectionForwardSelling)
{
    if (ModelState.IsValid)
    {
        db.tSectionForwardSellings.Add(tSectionForwardSelling);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.SectionID = new SelectList(db.tSections, "SectionID", "Section_Name", tSectionForwardSelling.SectionID);
    ViewBag.StoreID = new SelectList(db.tStores, "StoreID", "Store_Name", tSectionForwardSelling.StoreID);
    return View(tSectionForwardSelling);
}

这里是项目本身:https://drive.google.com/file/d/0BwgF9RnNTDDEOVlUMmxub2JxbFU/view?usp=sharing

防止用户将重复的数据发布到数据库中

您希望重复的数据存在吗?

如果表永远不包含超过1行相同的SectionName和StoreName值,那么您应该在数据库中通过在这两列上创建复合主键(聚集索引)或在这两列上创建唯一的非聚集索引来解决这个问题。

然后在你的。net MVC中,你也可以在插入数据时执行一些检查,以检查它是否已经存在,但你不会严格,你的数据库仍然不会进入一个坏的状态。

我将重复一些已经说过的内容,并添加一些想法。

首先:在数据库级别有一个约束,直接防止重复的场景。这通常是通过键完成的,某些类型的索引也可以强制执行此约束。

第二:在你向数据库添加任何必须是唯一的东西之前,从数据库中请求一个带有这些参数的对象的副本,如果它们存在,简单地更新记录,如果它们不存在,添加新的项。

第三步:如果它是一个在任何情况下都不能被复制的关键项,确保在第二步发出一个锁,这样其他人就不能对这个键做任何事情。锁将确保当您搜索该项目时,其他人无法在您搜索后添加该项目。

在我自己的系统中,我使用SQL级锁和基于缓存的分布式锁的组合。无论哪种方式,如果它是一个关键组件,您将希望开始更好地理解这种体系结构。在大多数非关键的低负载场景中,您可以使用简单的查找。