0

I am trying to update an entity Order using an object (i.e. order) which is sent from the UI.

I have the following in my method

Order neworder = new Order
        {
            ID = order.ID,
            FirstName = order.FirstName,
            LastName = order.LastName,
        };
        _bentities.Order.ApplyCurrentValues(neworder);

        _bentities.SaveChanges();

This works fine if I fill all the non-nullable values of entity Order. However I have only got few properties which are modified. I just want to update these modified properties (not all the non-nullable values which are not modified)

How can I do it?

I have read I can set the modified properties as:

var entry = _bentities.ObjectStateManager.GetObjectStateEntry(((IEntityWithKey)neworder).EntityKey);
        entry.SetModifiedProperty("FirstName");
        entry.SetModifiedProperty("LastName");

However this does not work for some reason. I get an exception that EntityKey cannot be null. How do I set the entitykey for neworder and then will this work?

gunnerz
  • 1,898
  • 5
  • 24
  • 39
  • you might want to see this post for your answer. [See here] (http://stackoverflow.com/questions/10257360/how-to-update-not-every-fields-of-an-object-using-entity-framework-and-entitysta) – patel.milanb Jul 13 '12 at 12:36

1 Answers1

0

If you're trying to update and entity, you'd have to fetch it from database first, and then call ApplkyCurrentValues.

order originalOrder = _bentities.Orders.FirstOrDefault(o => o.ID == updatedOrder.ID);
_bentities.Orders.ApplyCurrentValues(updatedOrder);
Kamyar
  • 18,639
  • 9
  • 97
  • 171