asp.net mvc models vs entity framework models

混江龙づ霸主 提交于 2019-12-03 03:15:35

The correct approach is using different class for ViewModel and different for a persistance (entity). The usual reason is that you often need to send some additional data to a view (for example data to fill drop downs, data to disable some fields etc.), use different validation or show only subset of an entity.

I'm not purist. If I see that my view model is exactly the same as the entity I use the entity directly but I will refactor the code once I need any additional information in the view. Most often I start with entities and I end with view models because of incremental development.

Usually I have my View Models in the Models folder, and my Domain Models in the ORM Layer.

View Models (from the name) are normal models for those objects you need only to aid the viewing process, they have no persistence whatsoever and they may contain some logic.

If you face the issue that your Domain Models match your View Models then you may need to re-design the models OR just use the Domain Models without a man-in-the-middle.

As for me I prefer deleting the Models folder in standard MVC structure and adding ViewModels folder where I store all the view models. As Ladislav mentioned at first iterations those viewmodels might be an exact copy of the entity from your Domain model but incrementaly they will grow an will differ a lot.

Well, it does not make sense. I used to struggling with this,I think you need to have model which is not the table entity, I called this domain model. The reason for that is sometimes if you are using the linq2sql, then you have to deal with the bridging/link table (which is not the real entity), and complex calculation, so you can't make it in your table entity, right? So my approach is to have ViewModel <-> Model <-> Entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!