Save disconnected object in entity framework 4

自闭症网瘾萝莉.ら 提交于 2019-12-12 18:19:30

问题


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


回答1:


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




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/4255581/save-disconnected-object-in-entity-framework-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!