我对一般的编程很新。我有一个包含3个表的数据库。一个名为User
的表,外键为TypeID
null,一个名为Login
的表,其外键UserID
为null,TypeID
为空,表为一个表以Types
为主键调用TypeID
。当我尝试更新我的实体模型时,收到Invalid InvalidOperationException
。
at System.Data.Objects.ObjectStateManager.ChangeObjectState(Object entity, EntityState entityState)
at MBMVCApplication.Controllers.LoginController.Edit(Users user, Int32 TypeID) in C:\Development\MBMVCApplication\Controllers\LoginController.cs:line 130
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.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
代码
[HttpPost]
public ActionResult Edit(Login login, int? typeID)
{
if (ModelState.IsValid)
{
db.Logins.Attach(login);
//TypeID display on a dropdown box
//I also remove the two line below and still get the error
login.User.TypeID = typeId.Value;
db.ObjectStateManager.ChangeObjectState(login, EntityState.Modified); //The error occurs here or
db.SaveChanges(); //Here
return RedirectToAction("Index");
}
ViewBag.UserID = new SelectList(db.Users, "UserID", "FirstName", login.UserID);
ViewBag.TypeID= new SelectList(db.Types, "TypeID", "Description", login.TypeID);
return View(login);
}
答案 0 :(得分:-1)
我不得不手动更新每个表格。我运行了一个查询来获取主ID;然后,我为模型创建了一个新对象,传递了从视图中选择的所有值,并使用主键更新了表。必须手动更新任何具有与该表关联的外键的表。这是耗时的,可能效率不高,但恰好是解决方法。