The relationship could not be changed because one or more of the foreign-key properties is non-nullable in MVC 4

StackOverflow https://stackoverflow.com/questions/23673182

  •  23-07-2023
  •  | 
  •  

Question

I am getting this error after click Save (update) my form:

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.

Here is my controller (case "Save" in swich couse problem):

[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);
    }
}

Any idea what is wrong...

Was it helpful?

Solution

try something like following.

foreach (var child in modifiedParent.ChildItems)
{
    context.Childs.Attach(child); 
    context.Entry(child).State = EntityState.Modified;
}
context.SaveChanges();

See the following link.

http://social.msdn.microsoft.com/Forums/en-US/1833117c-7a93-4b69-a133-b7fd764db810/the-operation-failed-the-relationship-could-not-be-changed-because-one-or-more-of-the-foreignkey?forum=adodotnetentityframework

OTHER TIPS

There is an easier way to solve this problem.
Actually this is because you have one to many relationship. When you want to delete 1 Side, you have two scenarios; You can choose cascade delete, or you can choose none.
If you select first option it will delete all the many side entities when you delete the 1 side. You can set this option in the Entity Diagram. You Only got to select the relationship and set "End1 OnDelete" property to Cascade.

I was experiencing this message, it turned out that I was marking the object as Modified after I had removed it from it's collection instead of deleting it.

For example you don't want to call context.Entry(child).State = EntityState.Modified;
if in fact you are trying to delete the child.

instead, as well as removing the child from the collection try something like context.DeleteObject(child)

  • I haven't got the exact code because my experience was with Dev Express XAF ObjectSpace which can be cast to ObjectContext using ((EFObjectSpace)objectSpace).ObjectContext;

I experienced this problem, it's complicated to explain (so please forgive the analogy), the good news is that the solution is very simple.

Assume I have a record with a one to many relationship, which also has a relationship. (A "Car" has a number of "People"; "People" have a number of "Children"). The error occurrs when removing people from car. Doing a db.Cars.Remove(person);. Caused an unrelated error. To resolve that issue I did a db.Cars.Persons.RemoveRange(children); <--- After this I experienced the error as stated in this question. To resolve this remove the child's children from the database (not the "Parent" but the database iteself) db.Children.RemoveRange(childrenOfPeople);.

This is the cleanest solution to the problem using entity framework correctly without setting the state of records. Hope that helps someone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top