I am using entity framework in my latest ASP.NET MVC 3 project. As it is DB first, the entity framework generates Database models. In my service (business) layer I Scaffold (MvcScaffolding) to generate service methods, views and controllers. Scaffolding also generates the domain models. When binding these models to the Views, I use view models.
In short, I ended up in using three types of models. Is this Ok? The view models are kept in the Presentation layer, domain models are kept in the business layer and data models are kept in the repository layer.
Please let me know your thoughts.
That sounds fine and indeed has several benefits.
You can recreate your database models from scratch without affecting the domain models, except how they are mapped of course. Some would argue that these two could be merged into one but it deeply depends on your setup.
Separate view models will allow you more freedom to change and create new viewmodels to suit your views. It also helps preventing late loading proxies etc.
Many people would also have a Dto set of objects. These come in useful as a set of objects for caching and also if you have more than one UI, say a windows service as well.
Automapper is very popular to ease the pain of having so many models to map.
It is good when you have differences between models on every level. If all you do with this models is put data from one layer model to another layer model without any transformation and processing, you can remove redundant models. In common cases domain model becomes redundant.
You should create separated viewmodel and database model due to necessity to have a possibility to recreate database model from database without changing of views.
来源:https://stackoverflow.com/questions/13469648/asp-net-mvc-view-model-domain-model-and-data-model