Store update, insert, or delete statement affected an unexpected . Entities modified or deleted since entities were loaded

asp.net-mvc asp.net-mvc-4 c# entity-framework

Question

I am using MVC for my project .

I added a controller named group and in this controller i have some action as usual like create and edit and etc .

but my problem refers to edit method As you can see here :

public ActionResult Edit(int GroupId)
{
    ViewBag.groupIdLST = new SelectList(OBJgroupRepository.FindBy(i => i.GroupId == null).ToList(), "Id",
    ViewBag.GroupType = new SelectList(OBJgroupRepository.FindBy(i => i.GroupId == null).ToList(), "name",
    DomainClass.Group tg = OBJgroupRepository.FindBy(i => i.Id == GroupId).First();
    return View(tg);
}
[HttpPost]
public ActionResult Edit(Group gr)
{
    if (ModelState.IsValid)
    {
        OBJgroupRepository.Edit(gr);
        OBJgroupRepository.Save();
    }
    TempData["success"] = "اطلاعات با موفقیت ویرایش شد";
    return RedirectToAction("Create");
}

When I click on edit button i got this error :

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.

My edit and save method :

public virtual void Edit(T entity)
{
    _entities.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}

public virtual void Save()
{
    try
    {
        _entities.SaveChanges();
    }
    catch (DbEntityValidationException e)
    {
        foreach (var eve in e.EntityValidationErrors)
        {
            Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                eve.Entry.Entity.GetType().Name, eve.Entry.State);
            foreach (var ve in eve.ValidationErrors)
            {
                Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                    ve.PropertyName, ve.ErrorMessage);
            }
        }
        throw;
    }
}

my repository :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DomainClass;
using ProjectModel;

namespace Repository
{
    public class GroupRepository : GenericRepository<DataAccessModelContainer, Group>
    {
    }
}

Any details are available as requested.

Best regards .

1
3
2/1/2015 1:54:12 PM

Popular Answer

The problem is here:

OBJgroupRepository.Edit(gr);
OBJgroupRepository.Save();

You called the OBJgroupRepository twice! This causes race condition (and subsequently concurrency consideration) between threads. Try to use save method contents inside edit.

4
2/1/2015 1:49:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow