I retrieve an object graph from DB using EF4. The context is closed as soon as the data retrieve and the data passes to the controller, and then to the view. in the view the data is modified, and then the controller gets it back.
From the controller I run Repository.Update(MyEmp);
and in my repository the code goes:
using (var context = new mydb())
{ if (myEmp.ID != 0) // Checking if it's modified or new { context.Emp.Attach(MyEmp); int result = context.SaveChanges(); return myEmp.ID; } }
The problem - once att开发者_如何学编程ached, the object entityState goes to unchanged, and not modified, and of course - nothing is saved to the database.
What am I doing wrong ?
Check my answer for this question about saving detached entities (second part). You have to manually set state to modified. Also check my answer about saving object graph. The problem is that you have to manually set state for every entity and relation in object graph.
I am using similar to below code for modified entities,
Context.TryGetObjectByKey(EntityKey, EntityInstance);
//EntityInstance:Nothing to do with your entity just create new instance and pass it to this method.
I guess Attach is not required.
精彩评论