Architecture – Where view models inside Web project of n-tier application should be placed

Architectureasp.net-mvcnet

Let's assume we have an ASP.NET MVC web application with following tiers:

  • Business logic
  • Entities (business domain and database POCOs)
  • Common (resources, consts)
  • Data access (database EF queries, EDMX EF models and so on)
  • Web application (MVC web application)

We're using view models approach. Currently view models are placed in Entities layer. Data access queries returns view models (due to efficiency issues, so we avoid using mapper).

Web layer references all other layers.
Data access references Common and Entities layers.
Business logic references Entities and Common layers, in the future also Data access layer.

There's an idea to move view models to Web layer. Why? Because they're in fact bound with a particular technology (MVC) and UI implementation.
But we're facing a problem here, because in this scenario Data access layer must reference Web and Web references Data access, so we have a circular dependency issue.

Moreover we have scenario when some validation of view model requires reference to Data access layer. We're going to keep validation method inside view models. Currently we want to implement it by injecting database context class (which is in Data access layer) to view model by constructor.

Do you have any idea how can we avoid it? Is it good idea to keep view models inside our Web layer?

Best Answer

I keep view models in the web project, for reason you stated, it's usually only useful to the relevant view.

I'm not sure why your data access layer would reference the web project though?