开发者

Entity Framework 4 POCO's and AutoMapper

开发者 https://www.devze.com 2023-02-12 21:19 出处:网络
I have been working on a new MVC application that utilizies EF4, POCO Domain Objects and the Repository <--> Service Layer开发者_开发百科.

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:

  • All View's have a ViewModel
  • POCO's have nothing but business/domain logic
  • ViewModel's have basic input validation
  • They are then mapped to the POCO's, which invoke domain/business validation

**Edit - in response to comments: **

Do your Repositories return IQueryable? If so, how do you handle the context? I mean does your Repositories implement IDisposable and then you dispose of them in the controllers?

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).

Where do you do your mapping at? Do you do it in 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!

0

精彩评论

暂无评论...
验证码 换一张
取 消