sto ottenendo questo errore dopo fare clic su Salva (aggiornamento) la mia forma:Il rapporto non potrebbe essere cambiato perché uno o più delle proprietà chiave esterna è non annullabile in MVC 4
Il rapporto non poteva essere modificato perché una o più proprietà della chiave esterna non sono annullabili. Quando viene apportata una modifica a una relazione, la relativa proprietà della chiave esterna viene impostata su un valore nullo. Se la chiave esterna non supporta valori nulli, deve essere definita una nuova relazione, la proprietà chiave esterna deve essere assegnata a un altro valore non nullo o l'oggetto non correlato deve essere eliminato.
Ecco il mio controller (caso "Salva" nel problema couse swich):
[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);
}
}
Qualsiasi idea di ciò che è sbagliato ...
Ok se cambia dbUser.CustomerTables.Remove (personalizzato); to dbContext.Entry (custom) .State = EntityState.Deleted; correggi il problema, ma poi aggiungi semplice (salva non funziona) –
possibile duplicato di [La relazione non può essere modificata perché una o più proprietà di chiave esterna non sono annullabili] (http://stackoverflow.com/questions/5538974/the-relationship-could-not-be-changed-because-one-or-more-of-the-foreign-pro-pro) –