2

in EF1, i couldn't just update an object that was constructed (with the right id) outside the scope of the ObjectContext.

Is there a new way in EF4?

Can i just add it to the context (context.AddOrder(order)) (where context is an instance of my ObjectContext) and 'it' sees that it has an id and updates it?

It's non-poco so my objects derive from EntityObject

Michel
  • 23,085
  • 46
  • 152
  • 242

3 Answers3

5

If it's a brand new object then you should use either ObjectContext.AddObject or ObjectSet.AddObject:
The AddObject method is for adding newly created objects that do not exist in the database. The entity will get an automatically generated temporary EntityKey and its EntityState will be set to Added.

On the other hand ObjectContext.Attach and ObjectSet.Attach is used for entities that already exist in the database. Rather than setting the EntityState to Added, Attach results in an Unchanged EntityState, which means it has not changed since it was attached to the context. Objects that you are attaching are assumed to exist in the database.

For a more detailed discussion on this topic, please take a look at this post:
Entity Framework 4 - AddObject vs Attach

Community
  • 1
  • 1
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
2

Use the Attach method instead. It is designed for disconnected objects.

Devart
  • 119,203
  • 23
  • 166
  • 186
  • i'n not sure, i have a newly constructed object, and the attach method is for objects 'when the object has an entity key'. Do i have an entity key when i just set the properties of an object? – Michel Nov 23 '10 at 14:06
  • Here is a code snippet to attach: context.Orders.Attach(order); context.ObjectStateManager.ChangeObjectState(order, System.Data.EntityState.Modified); order.SaveChanges(); – Devart Nov 24 '10 at 15:52
1

Taken from Employee Info Starter Kit, you can consider the code snippet as below:

public void UpdateEmployee(Employee updatedEmployee)
        {
            //attaching and making ready for parsistance
            if (updatedEmployee.EntityState == EntityState.Detached)
                _DatabaseContext.Employees.Attach(updatedEmployee);
            _DatabaseContext.ObjectStateManager.ChangeObjectState(updatedEmployee, System.Data.EntityState.Modified);
            _DatabaseContext.SaveChanges();
        }
Ashraf Alam
  • 3,500
  • 32
  • 31