views:

1465

answers:

2

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

+1  A: 

You shouldn't be updating your entity directly with the Form, I assume this also means you are sending the Order entity to your view in the GET?

Map the properties to a Dto/Resource/ViewModel/<Insert other overloaded, misused term here>.

That way the magic of UpdateModel cant set anything it shouldn't (including stopping hackers setting properties you dont want them to)

I suspect this will cure your issue as UpdateModel is probably cocking your entity up.

Do this first out of best-practice and see where you get ;)

Andrew Bullock
The Order entity is being passed to the View and renders the properties as Form input elements. Therefore as the entity properties are mapped by MVC to Order entity retrieved within the Edit method, it is this entity that I'm attempting to update rather than one passed out of context to the View. Mapping the properties manually was always an option but its not very flexible and the fact that EF4 has support for foreign-key properties and that MVC2 played nicely with EF4 doesn't bear out with the behaviour of UpdateModel. Or at least for more complex entity types with foreign key relationships
jbjon
if youre sending your Order entity to the view, the form will be typed to an Order when it posts back, which means UpdateModel will treat the contents of the POST body as relating to the properties of an Order. This means i could make a malformed request and update any properties I like on your Order entity. This is why you should use a DTO which only exposes the properties you want to allow users to update in the given action. When binding back from a post you can then transfer the changed properties onto your domain, safely.
Andrew Bullock
Letting an automatic modelbinder play around with your domain objects is a really bad idea, this issue youre having is just the tip of the iceberg. If you have loads of properties to map back and forth, consider using an AutoMapper.
Andrew Bullock
+2  A: 

I suspect it's tripping up on the OrderItemStatus. There is no way the formValues can contain the necessary OrderItem object, and thus the call to UpdateModel cannot possibly update it correctly. Perhaps it's setting it to null and orphaning an OrderItemStatus object in the process.

Before calling save changes, dump the contents of the ObjectStateEntries and take a look at what it's trying to save back to the database using code like:

var items = context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added | System.Data.EntityState.Modified);
foreach (var item in items)
{
  ...

You could also download the ASP.NET MVC2 code, link it in and step through UpdateModel to see what it's doing.

Hightechrider
Great suggestion. I'll get the source and step through to get to the bottom of this.
jbjon