开发者

Attaching object to EF 4 context from MVC view?

开发者 https://www.devze.com 2023-02-16 05:41 出处:网络
I am not sure if that makes any sense, but here is an example. I have a Category object, that my Service hands to the Controller, which uses AutoMapper to create a CategoryViewModel. Hand that off to

I am not sure if that makes any sense, but here is an example.

I have a Category object, that my Service hands to the Controller, which uses AutoMapper to create a CategoryViewModel. Hand that off to the view, serve it to the开发者_运维百科 client.

Now when that gets posted back, AutoMapper creates a Category from the Model sent back, and I hand it to the Service that gives it to the Repository to persist to the database.

My question is, what is the correct way of doing this? I assume the object is a detached object when posted back and I need to attach it to the context, mark it dirty and save changes?


Basically two ways of doing the update of the entity:

  1. Attach the entity to the context, mark it as modified using ObjectStateManager.ChangeObjectState Method, call ObjectContext.SaveChanges Method
  2. Load the original entity from DB, apply changes to the original using ObjectContext.ApplyCurrentValues<TEntity> Method, call ObjectContext.SaveChanges Method

Each of those have their own pros and cons. For example the 1st one does not make round trip to get the original entity but fails to address concurrency as well as tries to update every property of the entity, while the 2nd one works best when employing optimistic concurrency, updates only changed properties, but it does make extra trip to Db to get the original entity.


"I assume the object is a detached object when posted back and I need to attach it to the context, mark it dirty and save changes?"

Yes.

Any one of the links on this page should help:

http://www.google.com/search?rlz=1C1CHFX_enUS410US410&sourceid=chrome&ie=UTF-8&q=working+with+dicsonnected+entities+entity+framework

0

精彩评论

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