开发者

Save disconnected object in entity framework 4

in EF1, i couldn'开发者_如何学JAVAt 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


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


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


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();
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜