Bayrat
Bayrat

Reputation: 161

MVC3 EF model-first with POCO and ViewModels

Lots of great posts out here on this topic and I've tried to read them all. I'm a long time n-tier developer but trying to swing into action with an MVC3/EF application. I've generated POCOs via the EF POCO generator(T4). I'm also binding ViewModels to my Views...no EF stuff in my Views. My question has to do with validation (U/I only). I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels. From the advice I see on this site and others, I'll have to replicate any properties from my POCOs into my view models and do my annotations there. To make this easier I've seen lots of suggestions to use AutoMapper to make this tedious mapping more bearable.

Do I pretty much have the right idea?

Upvotes: 2

Views: 1349

Answers (2)

RPM1984
RPM1984

Reputation: 73123

I'm also binding ViewModels to my Views...no EF stuff in my Views

Correct. Ideally, your POCO's should not be on your Views.

I like the idea of DataAnnotations and want to use them. However, to use them correctly I have to use them in my ViewModels

Correct. There shouldn't be any data annotations on your POCO's.

From the advice I see on this site and others, I'll have to replicate any properties from my POCOs into my view models and do my annotations there

Why? Are you always binding to all of the properties on your POCO's? Remember, the ViewModel is to serve the View only. So if you have a form to submit an order, the ViewModel should only contain what is required to persist that Order. A combination of AutoMapper and your custom code can then map that to your POCO.

To make this easier I've seen lots of suggestions to use AutoMapper to make this tedious mapping more bearable

@Craig is right, it has nothing to do with Data Annotations. AutoMapper maps your ViewModel to your domain models with a few lines of configuration.

Upvotes: 4

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

AutoMapper is only about transformation from entity to view model and vice versa. It is just replacement of code like custom conversion operator between types. You will still have to create your view models and mark properties with correct data annotations.

Upvotes: 0

Related Questions