asp.net mvc models vs entity framework models

2019-03-15 07:43发布

问题:

Would it be best practice to create a model in your asp.net mvc - model folder. Use these models with your views and by using a service layer to "adapt" my model to the EF-model.

Or have you used another approach. The problem with this approachs is that most of the times my (selfmade)model is a copy of the EF-model (not dry)

So can someone explain me what models to use with your view cause it is becomming very confusing. model / viewmodel / Entityframeworkmodel ....

Solution :

Thanks for answers all guess i am at the moment to refactor some things!

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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