In MVC, 1 model 1 table or 1 model multiple tables?

In MVC, 1 model 1 table or 1 model multiple tables?

I am creating an application containing 3 tables. I do not know if I should create one model for all three tables or create 3 models for 3 tables.

In case I use 3 models for 3 tables, where should I put the code if I want to join these 3 tables? Put the code in any of the three models?

Any suggestions?

+4
source share
2 answers

Usually you create one model for each table, so in your case this means you need 3 models. When I say "Model", I mean a class that will be a single row (usually) in a single table.

for example: Tables:

  • Products
  • Orders
  • Customers

in this case, it is most easy and simple to create 3 different classes (which represents the application data model), where the first class represents the only product, the next represents the order and the last class will represent no customers.

+4
source

In general, the “Model” part of the MVC should be interpreted as the “View Model” or “View Model,” that is, the class that encapsulates all the data and behavior required for the view. This may or may not be equivalent to a domain model.

Domain models must be developed independently of the user interface. This means that such Models should not be contaminated with data and behavior specific to the user interface — for example, to determine whether a particular button is enabled or not.

You can also show the same domain objects in several different views (for example, "Master / Detail" or "Screen / Edit"), and if these views are sufficiently different, using a view model for each view will be useful.

So, in general, you must independently create your own domain layer and your presentation level.

At the domain level, you can select three tables for three classes. Books like Fowler Patterns Enterprise Application Architecture and Evans Domain-Driven Design contain many recommendations on how to model relational data as domain models.

When it comes to modeling representations in MVC, it makes sense to create one model per view. Such a view model can simply encapsulate one domain object, but it can also encapsulate and aggregate several different domain objects.

That way you can ensure that problems are shared and that your classes follow the principle of shared responsibility.

For very simple scenarios, it may make sense to collapse the domain model and model representation into one layer, but you should understand that this essentially means that there is no model domain in the solution - all models would not be purely Presentational models.

+5
source

Source: https://habr.com/ru/post/1286535/


All Articles