Is there an Update Object holder on Entity Framework?

时光毁灭记忆、已成空白 提交于 2019-12-08 17:32:29

Well if you have an object which is attached to the graph, if you modify values of this object, then the entity is marked as Modified.

If you simply do .AddObject, then the entity is marked as Added.

Nothing has happened yet - only staging of the graph.

Then, when you execute SaveChanges(), EF will translate the entries in the OSM to relevant store queries.

Your code looks a bit strange. Have you debugged through (and ran a SQL trace) to see what is actually getting executed? Because i can't see why you need that first .Save, because inline with my above points, since your modifying the entities in the first few lines of the method, an UPDATE statement will most likely always get executed, regardless of the ID.

I suggest you refactor your code to handle new/modified in seperate method. (ideally via a Repository)

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