views:

67

answers:

2

I've only discovered a month ago the folly of directly accessing entities / models from the data access layer of an n-tier app. After reading about ViewModels while studying ASP.NET MVC, I've come to understand that to make a truly extensible application the model that the UI layer interacts with must be different from the one that the Data Access layer has access to.

But what about the Business layer? Should I have a different set of models for my business layer as well? For true separation of concern, should I have a specific set of models that are relevant only to my business layer so as not to mess around with any entities (possibly generated by for example, the entity framework, or EJB) in the DAL or would that be overkill?

+1  A: 

Yes, you can. However, that particular solution complicates your code and leads to a bunch of POCOs that have similar properties and data, which is pointless.

The major point, however, it just to have a separation of the object used to render your view, and the object you use to represent the data.

Tejs
The complexity was what I was afraid of. So what's important is having the view separated and the business logic could be left to be dependent on whatever implementation the DAL provides?
Jonn
A: 

ASP.NET MVC is well served by the Model-View-ViewModel (MVVM) way of doing things. This means that each view gets ONE and ONLY ONE ViewModel, which is a custom-shaped Model that is dedicated to serving that View.

For example, if you have an Orders view that needs some OrderDetail and Customer data, create a ViewModel that exposes only the data from those Entities required by that View. The ViewModel serves to aggregate data together from multiple (or one, as necessary) entities.

Your Entities and business logic sit "under" the View/ViewModel layer and should be unaware of its implementation.

Dave Swersky
Does that mean that I should keep my business logic dependent on my DAL's implementation (which in this case is the Entity Framework)?
Jonn
Your business layer should have a dependency to the Entities, yes. In Entity Framework 4 those can be POCO (Plain Old CLR Objects).
Dave Swersky
Haven't bothered to look at EF 4 yet. Might give it a look see.
Jonn