I have been working on a new MVC application that utilizies EF4, POCO Domain Objects and the Repository <–> Service Layer.
I see a lot of talk about using AutoMapper to map the EF4 classes to the DTO for the View Models. I was under the impression that this was to get rid of the tightly bound EF4 classes. So my question is since I am using the POCO classes, can’t I just use those in the View Models? Or is there still a need for AutoMapper?
The argument is that your “POCO’s” are your domain models, and your View’s shouldn’t be concerned with Domain Models.
Think about it this way – data validation, if you want data annotations, you would have to put them on your POCO’s – but input validation (this field is required, etc) isn’t really a domain concern, it’s a UI concern – hence the use of ViewModels for Data Annotations and AutoMapper.
Of course, it’s not cut and dry, it’s a matter of preference.
I also use MVC/EF4/POCO/AutoMapper/Service Layer and i never bind to the POCO’s – i always use a ViewModel per View.
This way, you have a good level of consistency:
**Edit – in response to comments: **
Yes – my Repositories return
IQueryable<T>, where T is an aggregate root. My Repositories get passed a Unit of Work (which implements IDisposable). The Unit of Work is a wrapper for the EF4 context. StructureMap (DI container) is responsible for the lifetime of the components (including the UoW – aka the context). I new up a UoW per HTTP request and Dispose when it’s finished. My “Service” calls methods on my IQueryable repository and returns collections (e.g materializes the query before being passed back to the Controller).Up to you. Personally, i would create a static “bootstrapper” class that has a single method, e.g “Configure”. Call this once in your Application_Start event (Global.asax). This technique is decribed here.
Good luck!