Reputation: 635
I read a couple of articles and questions related to layered architecture in ASP.NET, however I got a bit confused after too much reading. The UI layer is developed in ASP.NET MVC and for the data access I use EF in my project.
I'd like to describe my problem through an example. Let's say I have a simple blog engine, with the following entities: Post, Comment, Category, User. I use EF database approach and generate POCO-s in my model layer to a data model class library, the generated datacontext and the EDMX goes to the data access library.
Above this I have a business layer. This is responsible for example to return a blog entry with comments. In my UI layer I'm using ViewModel classes because for displaying an entry I need both a Post entity and a list of Comments with usernames on the same view.
And now my problem: My view doesn't need every details of a User entity, just the name in order to display a post. The question is where should I do the mapping between my ViewModels and Model classes? Should the business layer do this? Or I should return the entities with every details and let the UI handle the mapping? Should the business layer contain ViewModels as a class library?
What is the best approach for this?
Upvotes: 3
Views: 655
Reputation: 5565
Hi I prefer using the ViewModel in UI layer. I read the book Pro ASP.NET MVC 3 Framework by Steven Sanderson. And in examples of this book, are a lot of ViewModels examples, I recomended read this book.
Upvotes: 1
Reputation: 1038710
The question is where should I do the mapping between my ViewModels and Model classes?
Ideally in a separate mapping layer. If you use AutoMapper mappings could be declared in separate files in the ASP.NET MVC project.
Should the business layer do this?
Absolutely not. The business layer has no knowledge of any view models.
Should the business layer contain ViewModels as a class library?
No. The UI layer (ASP.NET MVC application) is the only layer that has knowledge of view models. They could of course be in a separate class library if you wish, but it is only the UI layer that should reference it. View models are tightly coupled to views. And views are part of the UI.
Upvotes: 2