C# 存储更新、插入或删除语句受意外事件影响。自加载实体后已修改或删除的实体
我在我的项目中使用MVC 我添加了一个名为C# 存储更新、插入或删除语句受意外事件影响。自加载实体后已修改或删除的实体,c#,asp.net-mvc,entity-framework,asp.net-mvc-4,C#,Asp.net Mvc,Entity Framework,Asp.net Mvc 4,我在我的项目中使用MVC 我添加了一个名为group的控制器,在这个控制器中,我像往常一样执行一些操作,如创建和编辑等 但我的问题涉及到edit方法,您可以在这里看到: public ActionResult Edit(int GroupId) { ViewBag.groupIdLST = new SelectList(OBJgroupRepository.FindBy(i => i.GroupId == null).ToList(), "Id", ViewBag.Grou
group
的控制器,在这个控制器中,我像往常一样执行一些操作,如创建和编辑等
但我的问题涉及到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)。实体可能已被修改或删除,因为
实体已加载。看见
有关
理解和处理乐观并发异常
我的编辑和保存方法:
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>
{
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用DomainClass;
使用ProjectModel;
命名空间存储库
{
公共类组存储库:GenericRepository
{
}
}
如有需要,可提供任何详细信息
致以最诚挚的问候。问题在于:
OBJgroupRepository.Edit(gr);
OBJgroupRepository.Save();
您调用了
OBJgroupRepository
两次!这会导致线程之间的竞争条件(以及随后的并发考虑)。尝试在编辑中使用save方法内容。我知道这已经很晚了,但今天发生在我身上,我不知道为什么。我首先使用代码,必须对主键进行重大更改。当我这样做的时候,我开始犯同样的错误。我查看了大约2个小时,最后发现我试图将数据插入主键中。我想我会让人们知道这可能是你会犯这个错误的一个原因。这没有用?谢谢@AmirHosseinMehrvarzi我想知道为什么会发生这个错误?我在我的帖子中添加了repository@EA预览成功与否取决于使用一个线程(objectContext
)。我不知道你是怎么组织的。正如您在Microsoft网站上看到的,他们避免使用单独的方法进行编辑和保存!这就是发生在我身上的事情。我想知道如何绕过它,并且仍然能够将数据插入主键