开发者

Saving a modified object from ASP.NET MVC View Using Entity-Franework 4

开发者 https://www.devze.com 2023-02-01 10:27 出处:网络
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

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.

0

精彩评论

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