2

I'm new in programming, maybe my question is stupid, but I try to understand this concept right. In my small asp.net core web application I have entity classes, for example, product, a unit of measure for these products. I store them in a database, using entity framework. My entities are very simple and I pass them straight to the View (pulling them off a repository). My mentor says that in big serious projects people never do like this and it's not right at all, that in a well-written code View layer shouldn't know about entities and data layers at all, they should be totally independent. Does it mean that I should create ViewModel class for each View, even if they equal to my Entity classes? What are the best practices on this topic?

Hamed Moghadasi
  • 1,523
  • 2
  • 16
  • 34
  • have a look at [Why do we use ViewModels?](https://stackoverflow.com/a/14423126/2417602). You might get a clear understanding on ViewModels. – vikscool Feb 12 '20 at 06:42

2 Answers2

4

You most definitely shouldn't. These kinds of global rules rarely apply.

Let's see about the MVVM pattern:

A criticism of the pattern comes from MVVM creator John Gossman himself,[12] who points out that the overhead in implementing MVVM is "overkill" for simple UI operations.

I think that answers your question on creating a view model for everything.

If the model does not fit the view or is complicated enough then you can use ViewModel.

Your mentor's idea (I guess) is that you should always think in terms of Domain objects instead of database objects. But as you'll see in any example, there is no reason not to use a POCO object straight out of the db if it fits the view.

Hamed Moghadasi
  • 1,523
  • 2
  • 16
  • 34
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • By default MVC will allow the request to bind any property of the POCO. A malicious end user could start with the view object you gave them, then follow foreign keys and add / update any value reachable from that record. – Jeremy Lakeman Feb 13 '20 at 00:06
1

Though not a rule but it is practiced as standard in many projects. Entity objects are not directly passed on to your view. Please refer the link. For instance, you might want to hide some properties in the view. In such case if there is an intermediate class like Data Transfer Objects defined, client will be exposed only to the DTO class and not your DB class objects.