none
How could [httppost] insert duplicate records into SQL server database unintentionally? RRS feed

  • Question

  • I have developed an application in Asp.net MVC using Entity Framework. The application is up and running absolutely well until a day before yesterday when one of the users reported me that a single record has got entered into the database duplicating itself for around 500 times. The same user has entered around 650 entries without any issues before this unusual incident.

    Could someone explain why this could have happened and what precaution should be taken to prevent record being getting inserted unintentionally into the database creating several duplicate records?

    Sunday, March 26, 2017 11:14 AM

All replies

  • Hi ArunKhatri,

    >>Could someone explain why this could have happened and what precaution should be taken to prevent record being getting inserted unintentionally into the database creating several duplicate records?

    Based on your description, I would suggest that you could check if the records exist before you insert into database. like this:

    [HttpPost]
    public ActionResult Create([Bind(Include="Name,Family")] Class A a)
    {
    DbContext db = new DbContext();
    if(ModelState.IsValid)
    {
      if(db.A.Any(ac=>ac.Name.Equals(a.Name))
       {
          //TODO E.g. ModelState.AddModelError
          return;
       }
       else
       {
         db.A.Add(a);
    
         db.SaveChange();
       }
    }

    In addition, you could also use the RemoteValidation, for more information, please refer to:

    # Implement Remote Validation in ASP.NET MVC

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, March 28, 2017 6:39 AM
    Moderator