一般来说,我对编程很陌生。我有一个数据库,里面有 3 个表。一个User
外键为TypeID
空的表Login
,一个外键为UserID
空且不为空的表,以及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);
}