错误信息如下:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: 存储区更新、插入或删除语句影响到了意外的行数(0)。实体在加载后可能被修改或删除。刷新 ObjectStateManager 项。 ---> System.Data.OptimisticConcurrencyException: 存储区更新、插入或删除语句影响到了意外的行数(0)。实体在加载后可能被修改或删除。刷新 ObjectStateManager 项。 在 System.Data.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source) 在 System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) 在 System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) 在 System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) 在 System.Data.Entity.Internal.InternalContext.SaveChanges() --- 内部异常堆栈跟踪的结尾 --- 在 System.Data.Entity.Internal.InternalContext.SaveChanges() 在 System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 在 System.Data.Entity.DbContext.SaveChanges() 在 ContosoUniversity.Controllers.CourseController.Edit(Course course) 位置 d:\MVC\VS2012\ContosoUniversity\ContosoUniversity\Controllers\CourseController.cs:行号 91
我的model层:
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "Number")]
public int CourseID { get; set; }
[Required(ErrorMessage = "Title is required.")]
[MaxLength(50)]
public string Title { get; set; }
[Required(ErrorMessage = "Number of credits is required.")]
[Range(0, 5, ErrorMessage = "Number of credits must be between 0 and 5.")]
public int Credits { get; set; }
[Display(Name = "Department")]
public int DepartmentID { get; set; }
[ConcurrencyCheck]
[Timestamp]
public Byte[] Timestamp { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<Instructor> Instructors { get; set; }
}
我的Controller
//
// POST: /Course/Edit/5
[HttpPost]
public ActionResult Edit(Course course)
{
try
{
if (ModelState.IsValid)
{
db.Entry(course).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException e)
{
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "Name", course.DepartmentID);
ModelState.AddModelError(string.Empty, e.ToString());
}
return View(course);
}
页面用隐藏控件保存 Timestamp值,Course模型绑定时自动绑定,一定要是原来的值,可以防并发
有解决方法了吗? 我修改的t4模板,生成的时候把timestamp过滤掉的