views:

453

answers:

3

Earlier I created an AddClient page that (when posted) passed a client object and I used db.AddToClient(obj) in my repository to persist it. Easy stuff.

Now, I have a details page whose save submits a post to an action "UpdateClient". Before that action is hit, my custom model binder creates my Client object and it's conveniently handed to the action. The thing is, this client object is not connected to a EF context yet. Where is the correct place to do that? In the modelbinder, or maybe when we get it from the controller, or perhaps we wait until we do a repository call and link it up there? What's the recommended process?

A: 

Database work should be put in the repository call.

Are you directly binding to an entity framework object in your model binding? If not, you should consider do some mapping between your custom object and entity framework object.

J.W.
My db calls are in repository. What I'm trying to find out is when to call them to best leverage EF. As far as your question goes, I'm trying to determine that with these questions. It looks like I best use EF if I model bind querying the EF object early so it can use concurrency and better track state.
RailRhoad
I wouldn't expose the EF object directly to "model binding", I will use my own domain object or DTO, and map those object onto the EF object.
J.W.
A: 

If an EF object has been created outside a context, you need to Attach the object to the context.

See: http://msdn.microsoft.com/en-us/library/bb896271.aspx

Shiraz Bhaiji
If I wait to attach after I'm done with my object, don't I lose the benefits of EF's concurrency check? Also, does that Attach look at my object and sync it up to one in the db?
RailRhoad
Plus, attaching an object to the context leaves it an unchanged state. Wouldn't I want to query it first (before the model binding) and let it bind then. Then it could properly determine the state right?
RailRhoad
The Attached object will be a new object, if you want to update an existing object, you need first to get it from the database, make the changes and then save the changes.
Shiraz Bhaiji
+1  A: 

From what I remember, you will either need to attach the object again to the context and set it as modified

Or reload the object from the database and apply your changes.

This article explains it better:

http://msdn.microsoft.com/en-us/magazine/ee321569.aspx#id0090022

What version of EF are you using ?

Steve Ward