2012-12-06 80 views
1

我是相當新的一般prgramming。我有一個有3個表格的數據庫。稱爲User的表具有外部密鑰TypeID爲空,稱爲Login的表具有外部密鑰UserID null和TypeID非空,並且具有TypeID作爲主鍵的表稱爲Types。當我試圖更新我的實體模型時,我收到一個Invalid InvalidOperationException無法更新MVC3模型 - 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); 
} 

回答

-1

我不得不手動更新每個表。我運行了一個查詢來獲取主ID;然後,我爲模型創建了一個新對象,傳遞從視圖中選擇的所有值並使用主鍵更新表。任何具有與該表關聯的外鍵的表都必須手動更新。這很耗時,可能效率不高,但恰巧是解決方法。

+0

我們喜歡這裏的完整答案 - 請參閱[如何回答](http://stackoverflow.com/questions/how-to-answer)。 – Jesse