点击保存(更新)我的表单后,我收到此错误:
The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship,the related foreign-key property is set to a null value. If the foreign-key does not support null values,a new relationship must be defined,the foreign-key property must be assigned another non-null value,or the unrelated object must be deleted.
这是我的控制器(案例“保存”在swich couse问题):
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(UserModel userModel,string act = null,int idx = 0) { using (var dbContext = new userDbEntities()) { if (userModel.User == null) { userModel.User = new UsersTable(); } var newUser = userModel.User.userID == 0; userModel.CustomTypes = dbContext.CustomTypes.ToList(); switch (act) { case "addcustom": userModel.User.CustomerTables.Add(new CustomerTable { CustomType = new CustomType(),UsersTable = userModel.User }); break; case "deletecustom": userModel.User.CustomerTables.RemoveAt(idx); break; case "save": foreach (var customer in userModel.User.CustomerTables) { customer.CustomType = dbContext.CustomTypes.Find(customer.CustomType.Id_NewCustomerType); } var dbUser = dbContext.UsersTables.Find(userModel.User.userID); dbUser.TimeZoneId = userModel.User.TimeZoneId; foreach (var custom in userModel.User.CustomerTables) { if (custom.CustomerID == 0) dbUser.CustomerTables.Add(custom); } foreach (var custom in dbUser.CustomerTables.ToList()) { var modelCustom = userModel.User.CustomerTables.FirstOrDefault(o => o.CustomerID == custom.CustomerID); if (modelCustom != null) //update it { custom.CustomType = dbContext.CustomTypes.Find(modelCustom.CustomType.Id_NewCustomerType); } if (userModel.User.CustomerTables.All(o => o.CustomerID != custom.CustomerID)) dbUser.CustomerTables.Remove(custom); } dbContext.SaveChanges(); break; } // end switch statements return View("Edit",userModel); } }
任何想法是什么错误…
解决方法
尝试如下所示.
foreach (var child in modifiedParent.ChildItems) { context.Childs.Attach(child); context.Entry(child).State = EntityState.Modified; } context.SaveChanges();
请参阅以下链接.