System.Data.Entity.Infrastructure.DbUpdateConcurrencyException HResult=0x80131501 Message=Store update, insert, or delete statement affected an unexpected number of rows (0).

Phạm Thanh Lam 0 Reputation points
2024-11-18T17:56:30.2966667+00:00

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.Entity;

using System.Data.Entity.Infrastructure;

using System.IO;

using System.Linq;

using System.Net;

using System.Web;

using System.Web.Mvc;

using WebApplication1.Models;

namespace WebApplication1.Controllers

{

public class DestinationsController : Controller

{

    private DBDuLich2Entities db = new DBDuLich2Entities();

    // GET: Destinations

    [Authorize(Roles = "Admin")]

    public ActionResult Index()

    {

        var destinations = db.Destinations.Include(d => d.Map);

        return View(destinations.ToList());

    }

    // GET: Destinations/Details/5

    [Authorize(Roles = "Admin")]

    public ActionResult Details(int? id)

    {

        if (id == null)

        {

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

        }

        Destination destination = db.Destinations.Find(id);

        if (destination == null)

        {

            return HttpNotFound();

        }

        return View(destination);

    }

    // GET: Destinations/Create

    [Authorize(Roles = "Admin")]

    public ActionResult Create()

    {

        ViewBag.destination_id = new SelectList(db.Maps, "Map_Id", "Destination_Name");

        return View();

    }

    // POST: Destinations/Create

    [HttpPost]

    [ValidateAntiForgeryToken]

    [Authorize(Roles = "Admin")]

    public ActionResult Create([Bind(Include = "destination_name,description,imageDes")] Destination destination, HttpPostedFileBase imageDes)

    {

        if (ModelState.IsValid)

        {

            // Xử lý ảnh (nếu có)

            if (imageDes != null && imageDes.ContentLength > 0)

            {

                var fileName = Path.GetFileName(imageDes.FileName);

                var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);

                imageDes.SaveAs(path);

                destination.imageDes = fileName; // Lưu tên tệp vào thuộc tính imageDes

            }

            // Thêm mới destination vào cơ sở dữ liệu

            db.Destinations.Add(destination);

            db.SaveChanges();

            // Chuyển hướng về Index sau khi lưu thành công

            return RedirectToAction("Index");

        }

        // Nếu ModelState không hợp lệ, trả lại dữ liệu về View

        ViewBag.destination_id = new SelectList(db.Maps, "Map_Id", "Destination_Name", destination.destination_id);

        return View(destination);

    }

    // GET: Destinations/Edit/5

    [Authorize(Roles = "Admin")]

    public ActionResult Edit(int? id)

    {

        if (id == null)

        {

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

        }

        // Tìm đối tượng trong cơ sở dữ liệu theo id

        Destination destination = db.Destinations.Find(id);

        if (destination == null)

        {

            return HttpNotFound();

        }

        // Truyền thông tin của destination vào View

        ViewBag.destination_id = new SelectList(db.Maps, "Map_Id", "Destination_Name", destination.destination_id);

        return View(destination);

    }

    // POST: Destinations/Edit/5

    [HttpPost]

    [ValidateAntiForgeryToken]

    [Authorize(Roles = "Admin")]

    public ActionResult Edit([Bind(Include = "destination_id,destination_name,description,imageDes")] Destination destination)

    {

        if (ModelState.IsValid)

        {

            db.Entry(destination).State = EntityState.Modified;

            db.SaveChanges();

            return RedirectToAction("Index");

        }

        ViewBag.destination_id = new SelectList(db.Maps, "Map_Id", "Destination_Name", destination.destination_id);

        return View(destination);

    }

    // GET: Destinations/Delete/5

    [Authorize(Roles = "Admin")]

    public ActionResult Delete(int? id)

    {

        if (id == null)

        {

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

        }

        Destination destination = db.Destinations.Find(id);

        if (destination == null)

        {

            return HttpNotFound();

        }

        return View(destination);

    }

    // POST: Destinations/Delete/5

    [HttpPost, ActionName("Delete")]

    [ValidateAntiForgeryToken]

    [Authorize(Roles = "Admin")]

    public ActionResult DeleteConfirmed(int id)

    {

        Destination destination = db.Destinations.Find(id);

        if (destination == null)

        {

            return HttpNotFound();

        }

        db.Destinations.Remove(destination);

        db.SaveChanges();

        return RedirectToAction("Index");

    }

    public ActionResult DestinationList()

    {

        var des = db.Destinations.Include(p => p.Trips);

        return View(des.ToList());

    }

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            db.Dispose();

        }

        base.Dispose(disposing);

    }

}
```}

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException

  HResult=0x80131501

  Message=Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See [http://go.microsoft.com/fwlink/?LinkId=472540]() for information on understanding and handling optimistic concurrency exceptions.

  Source=EntityFramework

  StackTrace:

   at System.Data.Entity.Internal.InternalContext.SaveChanges()

   at WebApplication1.Controllers.DestinationsController.Edit(Destination destination) in D:\Agodaa\WebApplication1\Controllers\DestinationsController.cs:line 112

   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)

   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState)

   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)

   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0()

   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2()

  This exception was originally thrown at this call stack:

[External Code]


OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See [http://go.microsoft.com/fwlink/?LinkId=472540]() for information on understanding and handling optimistic concurrency exceptions.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
757 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,951 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,067 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Hongrui Yu-MSFT 3,015 Reputation points Microsoft Vendor
    2024-11-19T05:51:22.5266667+00:00

    Hi,@Phạm Thanh Lam. Welcome to Microsoft Q&A. 

    According to your error message, you seem to have encountered a concurrency error when saving data into the database.

    GUID and Timestamp are concurrency tokens used to detect whether the system has concurrency errors. When a concurrency error occurs, a DbUpdateConcurrencyException exception is thrown.

    You could catch the exception and decide which value to store in the database. You could refer to the following writing.

        try
        {
            db.SaveChanges();
        }
    
        catch (DbUpdateConcurrencyException ex)
        {
            foreach (var entry in ex.Entries)
            {
                if (entry.Entity is Destination)
                {
                    var proposedValues = entry.CurrentValues;
                    var databaseValues = entry.GetDatabaseValues();
    
                    foreach (var property in proposedValues.Properties)
                    {
                        var proposedValue = proposedValues[property];
                        var databaseValue = databaseValues[property];
     
     // TODO: decide which value should be written to database 
     // proposedValues[property] = proposedValue;
                    }
    
     
                    // Refresh original values to bypass next concurrency check
                    entry.OriginalValues.SetValues(databaseValues);
                    // db.SaveChanges();
                }
                else
                {
                    throw new NotSupportedException(
                        "Don't know how to handle concurrency conflicts for "
                        + entry.Metadata.Name);
                }
            }
        }
    

    For more detailed information on how to handle concurrency conflicts when using Entity Framework Core, please refer to the official documentation.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.