Using MVC2 to update an Entity Framework v4 object with foreign keys fails

Posted by jbjon on Stack Overflow See other posts from Stack Overflow or by jbjon
Published on 2010-05-19T21:02:36Z Indexed on 2010/05/20 3:00 UTC
Read the original article Hit count: 809

With the following simple relational database structure: An Order has one or more OrderItems, and each OrderItem has one OrderItemStatus.

Order, OrderItem and OrderItemStatus tables linked with foreign key relationships Entity Framework v4 is used to communicate with the database and entities have been generated from this schema. The Entities connection happens to be called EnumTestEntities in the example.

The trimmed down version of the Order Repository class looks like this:

public class OrderRepository
{
  private EnumTestEntities entities = new EnumTestEntities();

  // Query Methods
  public Order Get(int id)
  {
    return entities.Orders.SingleOrDefault(d => d.OrderID == id);
  }

  // Persistence
  public void Save()
  {
     entities.SaveChanges();
  }
}

An MVC2 app uses Entity Framework models to drive the views. I'm using the EditorFor feature of MVC2 to drive the Edit view.

When it comes to POSTing back any changes to the model, the following code is called:

[HttpPost]
public ActionResult Edit(int id, FormCollection formValues)
{
  // Get the current Order out of the database by ID
  Order order = orderRepository.Get(id);
  var orderItems = order.OrderItems;

  try
  {
    // Update the Order from the values posted from the View
    UpdateModel(order, "");
    // Without the ValueProvider suffix it does not attempt to update the order items
    UpdateModel(order.OrderItems, "OrderItems.OrderItems");

    // All the Save() does is call SaveChanges() on the database context
    orderRepository.Save();

    return RedirectToAction("Details", new { id = order.OrderID });
  }
  catch (Exception e)
  {
    return View(order); // Inserted while debugging
  }
}

The second call to UpdateModel has a ValueProvider suffix which matches the auto-generated HTML input name prefixes that MVC2 has generated for the foreign key collection of OrderItems within the View.

The call to SaveChanges() on the database context after updating the OrderItems collection of an Order using UpdateModel generates the following exception:

"The operation failed: 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."

When debugging through this code, I can still see that the EntityKeys are not null and seem to be the same value as they should be. This still happens when you are not changing any of the extracted Order details from the database. Also the entity connection to the database doesn't change between the act of Getting and the SaveChanges so it doesn't appear to be a Context issue either.

Any ideas what might be causing this problem? I know EF4 has done work on foreign key properties but can anyone shed any light on how to use EF4 and MVC2 to make things easy to update; rather than having to populate each property manually. I had hoped the simplicity of EditorFor and DisplayFor would also extend to Controllers updating data.

Thanks

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about entity-framework-4