【问题标题】:Store update, insert, or delete statement affected an unexpected . Entities modified or deleted since entities were loaded存储更新、插入或删除语句影响了意外的 .自加载实体后修改或删除的实体
【发布时间】:2016-07-17 10:20:33
【问题描述】:

我正在为我的项目使用 MVC。

我添加了一个名为 group 的控制器,在这个控制器中我有一些像往常一样的操作,例如 createedit 等等。

但我的问题是指edit 方法如您在此处看到的:

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

当我点击编辑按钮时出现此错误:

存储更新、插入或删除语句影响了意外 行数 (0)。实体可能已被修改或删除 实体已加载。看 http://go.microsoft.com/fwlink/?LinkId=472540 获取有关信息 理解和处理乐观并发异常。

我的编辑和保存方法:

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

我的仓库:

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>
    {
    }
}

可根据要求提供任何详细信息。

最好的问候。

【问题讨论】:

标签: c# asp.net-mvc entity-framework asp.net-mvc-4


【解决方案1】:

问题出在这里:

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

你打了两次OBJgroupRepository!这会导致线程之间的竞争条件(以及随后的并发考虑)。 尝试在编辑中使用保存方法内容。

【讨论】:

  • 我在帖子中添加了我的存储库
  • @EA 您的预览成功取决于使用一个线程 (objectContext)。不知道你是怎么组织的。正如您在 Microsoft 网站上看到的,他们避免使用单独的方法来执行 editsave!
【解决方案2】:

我知道这已经晚了,但今天发生在我身上,我不知道为什么。我首先使用代码,并且必须对主键进行重大更改。当我这样做时,我开始遇到同样的错误。我研究了大约 2 个小时,最后发现 我正在尝试将数据插入主键。我想我会让人们知道这可能是您收到此错误的原因。

【讨论】:

  • 这就是发生在我身上的事情。我想弄清楚如何绕过它并且仍然能够将数据插入主键
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多