Entity Framework 4 POCO and AutoMapper

I am working on a new MVC application that uses EF4, POCO domain objects, and the Service storage tier.

I see a lot of talk about using AutoMapper to map EF4 classes to DTO for view models. I got the impression that this was supposed to get rid of the closely related EF4 classes. So my question is that I am using POCO classes, can I use them in view models? Or is there still a need for AutoMapper?

+4
source share
1 answer

The argument is that your “POCOs” are your domain models, and your View should not concern domain models.

Think of it this way: data validation, if you want data annotations, you will have to put them in your POCO, but input validation (this field is required, etc.) is not really a problem for the domain, this is the user interface is a concern - hence Using ViewModels for data annotations and AutoMapper.

Of course, this is not cut and dried, it is a matter of preference.

I also use MVC / EF4 / POCO / AutoMapper / Service Layer and never get attached to POCO - I always use ViewModel for every view.

So you have a good level of consistency:

  • All views have a ViewModel.
  • POCO has nothing but business logic.
  • ViewModel has basic input validation
  • Then they are displayed in POCO, which cause domain / business verification

** Edit - in response to comments: **

Are your IQueryable repositories restored? If so, how do you handle the context? I mean, do your repositories implement IDisposable and then you delete them in controllers?

Yes - my repositories return an IQueryable<T> , where T is the aggregate root. My repositories get the transferred 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 components (including UoW, as well as context). I update UoW for each HTTP request and remove it when done. My "Service" calls methods in my IQueryable repository and returns collections (for example, materializes the request before it is passed back to the controller).

Where do you do your mapping? Are you doing this in the controller?

To you. Personally, I would create a static class "bootstrapper" that has one method, for example, "Configure". Call it once in your Application_Start application (Global.asax). This method is described here .

Good luck

+13
source

Source: https://habr.com/ru/post/1341084/


All Articles