1

一般来说,我对编程很陌生。我有一个数据库,里面有 3 个表。一个User外键为TypeID空的表Login,一个外键为UserID空且不为空的表,以及TypeID一个作为主键的表。当我尝试更新我的实体模型时,我收到一个.TypesTypeIDInvalid 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);
}
4

1 回答 1

-1

我不得不手动更新每个表。我运行了一个查询来获取主 ID;然后,我为模型创建了一个新对象,传递从视图中选择的所有值,并使用主键更新表。任何具有与该表关联的外键的表都必须手动更新。这很耗时,可能效率不高,但它恰好是解决方法。

于 2013-04-05T01:51:49.027 回答