in this MVC tutorial it showed how to decouple Controller from database logic using Repository and a Service layer. However the example is for a very simple model of pure properties. What about associations?
Say if Product model has an association to the Users table through Owner association. The controller calls the service or the repository to get a list of users, pass it to View, and View displays the users as a drop-down list.
Then on a standard POST: product/Create, controller needs to get the chosen userID, then grab the User entity of that id, and associate it with the to be created Product.
if (!String.IsNullOrEmpty(Request['SelectedUserId'])) { int selectedUserId = Convert.ToInt16(Request['SelectedUserId']); newProduct.Owner = _productService.GetUserById(ownerId); } _productService.AddProduct(newProduct);
But this process complicates the controller logic. Even worse if we need to validate the associations (since there wouldn’t be OnChanging events for the associations, we can’t do it in the Model partial class).
My question is, is there any better way to handle associations? Is it better to pass the Request parameters to the service layers as well and do everything there? What about validations?
Update: (after the comment on it not being linq2sql)
In your specific scenario (based on your desc + the code you posted), I would definitely move the load down to the service layer. This doesn’t mean moving the request down to it. I would refactor as:
I also usually have an extension method like T
oNullable<int>(), that makes it:Depending on the emphasis you give to models, you can have something that contains both fields, like CustomerProduct.
If you are persisting with linq2sql, you don’t need to get the User to do that in this scenario. Linq2sql will generate an OwnerId property, which you can use without having to go the db to get it.
Having the model tied for different sub-systems is not always the best approach when dealing with complex models. This is more important if you have parts of the system that are appropriate for their own bounded context. When that’s the case, the above has even more importance, as you want to have really clear and specific places to integrate the 2 bounded contexts.
Besides the above, there are some times when it is appropriate to have some extra glue for these type of processes. Consider adding a service class to help you on it. This doesn’t mean that everything needs to go through a service class or that the domain objects wouldn’t have the logic, its just there for the specific scenarios where you need the extra actions that isn’t appropriate for either the domain objects or the controllers.