自实体加载后,实体可能已被修改或删除。刷新ObjectStateManager条目

时间:2014-10-15 07:09:08

标签: asp.net-mvc entity-framework concurrency ef-code-first

我面临并发问题。

Student类包含MandatoryInformation,Basic,FeeInformation,StudentClass,ContactInformation和Address对象。

我的来源位于:

https://www.dropbox.com/s/e34frntq8u5gsmh/SchoolManagementSystem.rar?dl=0

现在我方法的定义如下:

public ActionResult Create(Student student, HttpPostedFileBase Image)
{
    try
    {
        if (ModelState.IsValid)
        {
            //student = db.Students.Find(student.ID);
            if (student != null && student.ID > 0)
            {
               // var studentOrg = db.Students.Find(student.ID);
               // db.Entry(studentOrg).CurrentValues.SetValues(student); 
                db.Entry(student).State = EntityState.Modified;
                if (student.MandatoryInformation != null && student.MandatoryInformation.ID > 0)
                {
                    db.Entry(student.MandatoryInformation).State = EntityState.Modified;
                }
                if (student.Basic != null && student.Basic.ID > 0)
                {
                    db.Entry(student.Basic).State = EntityState.Modified;
                }
                if (student.FeeInformation != null)
                {
                    db.Entry(student.FeeInformation).State = EntityState.Modified;
                }
                if (student.StudentClass != null)
                {
                    db.Entry(student.StudentClass).State = EntityState.Modified;
                }
                if (student.ContactInformation != null)
                {
                    db.Entry(student.ContactInformation).State = EntityState.Modified;
                }
                if (student.Address != null)
                {
                    db.Entry(student.Address).State = EntityState.Modified;
                }

                db.SaveChanges();
            }
            else
            {
                if (student.Basic == null) student.Basic = new BasicInformation();
                if (Image != null && Image.ContentLength > 0)
                {
                    student.Basic.PictureUrl = Image.FileName;
                    string path = Server.MapPath(("~/Images/"));
                    Image.SaveAs(path + Image.FileName);
                }

                db.Students.Add(student);
                db.SaveChanges();
            }
            return RedirectToAction("StudentList");
        }
    }
    catch (RetryLimitExceededException /* dex */)
    {
        //Log the error (uncomment dex variable name and add a line here to write a log.
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
    }
    return View(student);
}

我得到了这个例外:

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException was unhandled by user code
      HResult=-2146233087
      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. Refresh ObjectStateManager entries.
      Source=EntityFramework
      StackTrace:
           at System.Data.Entity.Internal.InternalContext.SaveChanges()
           at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
           at System.Data.Entity.DbContext.SaveChanges()
           at SMSApp.Controllers.RegistrationController.Create(Student student, HttpPostedFileBase Image) in c:\Users\mehmood.ahmed.SOFTECH\Downloads\SchoolManagementSystem\SchoolManagementSystem\SMSApp\Controllers\RegistrationController.cs:line 162
           at lambda_method(Closure , ControllerBase , Object[] )
           at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
           at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
           at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
           at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
           at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
           at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
           at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
           at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
           at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
           at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
           at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41()
      InnerException: System.Data.Entity.Core.OptimisticConcurrencyException
           HResult=-2146233087
           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. Refresh ObjectStateManager entries.
           Source=EntityFramework
           StackTrace:
                at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source)
                at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
                at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
                at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction, Boolean throwOnClosedConnection)
                at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update(Boolean throwOnClosedConnection)
                at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__33()
                at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
                at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy)
                at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass28.<SaveChanges>b__25()
                at System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
                at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
                at System.Data.Entity.Internal.InternalContext.SaveChanges()
           InnerException: 

1 个答案:

答案 0 :(得分:1)

谢谢大家。我的问题解决了。我错过了隐藏的领域。现在工作正常。下面的陈述是解决方案。

@Html.HiddenFor(mbox => mbox.ID) 
@Html.HiddenFor(mbox => mbox.FeeInformation.ID) 
@Html.HiddenFor(mbox => mbox.Basic.ID) 
@Html.HiddenFor(mbox => mbox.ContactInformation.ID) 
@Html.HiddenFor(mbox => mbox.MandatoryInformation.ID) 
@Html.HiddenFor(mbox => mbox.StudentClass.ID) 
@Html.HiddenFor(mbox => mbox.Address.ID)