views:

80

answers:

1

When creating a new entity object that has a foreign key value I need to create a new Entity key (Entity Framework in .net 3.5) for the object, but I'm having trouble deciding where in my application I should do this.

Right now when I create a new record with a foreign key, I create the entity key in the controller (in this case a user ID pulled from a membership provider), assign it to the object and pass it to the repository service layer.

Are there any problems with this, or should I be passing the object plus the user ID to the repository service layer and have it deal with the entity key creation? Passing one object seems cleaner, but having multiple controllers assigning keys this way makes me nervous. Thanks.

+4  A: 

I think this is a matter of separation of concerns. A repository is concerned with retrieving and adding/changing/removing entities. It shouldn't be responsible for building entities. Conversely, the controller really shouldn't be responsible for building entities either (a controller should to the bare-bones amount of work required to push data to a view, and handle commands from a view delegate those commands to business logic...business logic belongs elsewhere (like a domain).) In all honesty, you should create an EntityBuilder of some sort to handle the process of creating entities. You would pass the object plus user ID to a builder, which would then provide you with a fully built entity that could then be passed on to a repository.

EDIT:

Even with your change from 'Repository' to 'Service Layer', the principal remains the same. Delegate the process of building your entity to a dedicated builder, and maintain your separation of concerns.

jrista
Your answer is very sensible. I didn't understand the question.
Cyril Gupta
I misspoke, that should actually say "service layer" instead of "reposity" from your post it sounds like this would indeed be the place to either handle the entity creation.
Graham
That makes sense, thanks for your insight.
Graham