Queries on Repository Layer in MVC application - asp.net-mvc

I am building MVC 5 application using Razor.
My application is layered as below:
UI Layer: Comprising of Model, View and Controller.
Data Access Layer: Connection and Stored Procedure classes
Business Layer (Service Layer)
Repository
I referred to Contosso Sample Application. There it is using DAL to store Repository. But I am creating a separate layer.
I want to know:
Whether to keep Repository as a separate layer or in DAL?
UI layer Model holds View Models. Where does other models go? Do they reside in Repository Layer? Are these called POCO?

Usually, the Repository is the method of accessing the data and is therefore just an implementation technique of the DAL. I'd combine them both as the DAL.
In terms of other models, I assume you mean the classes that correspond with your data items. These should also live in the DAL/Repository layer. They are referred to as POCOs as they don't contain any implementation, simply a list of properties (plain old CLR object).

Related

Why should we add Model reference separately to MVC front end instead of using it from service reference?

In older web projects that I worked on, we used to create models in DAL, add reference of DAL in Business Logic Layer (and reuse models from DAL as they would be available with reference of DAL), Add reference of BL in Service (again reuse models). Entities were available transitively in all successive layers.
In a MVC project with multiple layers, Models are often added in a separate class library project and referenced across all layers like DAL, Business Logic, Service, FrontEnd etc; Even though they are transitively available.
Is there any specific reason to do this? Why shouldn't we bind Models available through service in frontend like below
#model List<TestSolution.TestServiceRef.Employee>
instead of
#model List<TestSolution.Models.Employee>
What is the advantage of referring models separately in all layers over using it from the reference of another/previous layer?
I don't have a lot of MVC experience (as far as ASP.Net MVC), but as I understand it the Model in MVC is just a representation of the data structures as the coded understands it (i.e. at runtime) - and isn't necessarily the underlying data itself (i.e. database).
If you have a concept that you want to represent in the UI, then obviously the UI needs to know what that concept is - hence referencing it at that level (and other such as the business logic, etc). Pre MVC there was an approach / architecture I followed where the "model" was just a bunch of POCO's (plain old class objects - .e. really simple dumb classes or structs).
These POCO's could go into a an assemply/project like MyApp.Common from where you could safely reference them in any other project / layer of the architecture (UI, Logic, DAL, etc). This allows all layers of the application to "talk the same language", so to speak.
I did a proper write up of this architectural style (which is not MVC, but shares some concepts), here: https://morphological.wordpress.com/2011/08/29/5-layer-architecture/

MVC architecture large action method on controller

I'm currently developing business logic in a Controller's ActionResult function, and I've noticed it's becoming unwieldy... large... involves a lot of page ups/downs.
Code includes populating lists for dropdownlists assigned to ViewBag properties, but most of the size is taken up EF (linq to entities) and in memory processing of this.
And finally sent to a view model via Auto Mapper.
Where is the best place to move this code? In another class in the Controllers folder? Or in another class in another folder, i.e. a Business layer?
Separate you project to :
WebUI(View, Controller-A MVC Project)
Business Layer(Holds Business Logic - A class Library Project )
Data Access Layer(Holds Entity Model(May be EDMX) - A class Library Project)
A controller of WebUI project call method of business layer.
If business need data from database then, it will call Data Access Layer.
Funnily enough I answered a very similar question yesterday. In a nutshell, limit your controller to just the minimum logic to link your models with your views. Business logic, data access etc. is better placed in a separate repository.
Bappi Datta is right. Let me just explain it from my point of view.
My best practice with the libs AutoMapper, EF is:
Web - includes logic of rendering, some validation, bootstrap configuration. Calls Business layer methods and classes.
Web.Models - web models with validation attributes
BusinessLogic - business layer. Includes mappings EF Entities <---> Web.Models. Uses Data classes.
Data - Here I always put EF Models and context. Also implementation of Repository pattern could be placed there.
You need to have Repository Layer (which you mentioned you already have) and then you need to have a Service Layer which will hold all your necessary business logic probably using patterns like Command Factory and Facades. Then in order for you to have a flexible and easily pluggable architecture, you need to use Dependency Injection between all layers.
Read about MVC architecture in my perspective
There can be different If's and But's in the theoretical discussion of overall MVC architecture itself. But generally your controller actions needs to be thin, you business logic needs to be in a different layer other than repository.

Application design using DDD

I am designing solution strucure for an application. I am planning to use Domain driven design. Asp.net MVC and Entity framework. Need your inputs in some areas.
Data Access is designed using Entity framework code first
Reposirotires are built on top of EF Data Acces
Domain model is designed usind domain model on top of Repositories
Application serveices are built on top of Damain layer
UI is developed on top of Application services
The flow is
UI (controller) --> Application service --> Domain Layer --> Repositories --> Data Access --> Data base.
I am not very clear of how to share the data in between the layers.
My Domain model can be used to sahre data between Repositories, Data Access and Domain Layer. I am just thinking the way the data should be passed from Daomin Layert to Application Service and Application Service to UI. I can use DTOs, But not sure weather it is a good option or not, as i have some models are already in Domain Model, View model in UI.
Reuse Domain Model or UI Model is not good, it will make your layers are tightly coupled. It's very difficult to develop large scale applications that way.
What you think is correct, Application is a thin layer, it's just a bunch of Actions which will be called directly from UI layer and information will be passed through an object called ActionParameter. ActionParameters are defined in Application layer and ActionParameter objects are constructed on UI layer and passed to Application layer.
Application will retrieve data from DB via Data Access Layer. An Query Action sometimes need to fetch data from many source, different domain entities and data need to be projected, transformed or formatted before return to UI layer. We will have something like ActionResult objects that contains all data to be returned to UI layer.
It seems there will be a lot of codes but I think it's necessary. Each layer has its own purpose and when we change one, other layers won't be impacted.
Given the flow you describe, create view models in the UI layer to be instantiated by the controller. A view model is simple object to which the view binds. This should be decoupled from the underlying domain model to address concerns noted by namkha87.
As far as the data access layer, you can use the domain objects themselves for object-relational mapping since EF allows this. There is no need for an intermediate DTO here.
Another thing to consider is separating the model used for queries from one's used to invoke behavior. This way, you can ensure that an application service never exposes behavioral domain objects, only read-models. The problem with having an application service expose domain objects to outer layers is that it will allow those outer layers to invoke behaviors on those objects the results being undefined. When you only return read-only objects with no behaviors, this isn't a problem. For data coming back, don't have the UI layer created domain objects directly - you should distinguish between entities and simple data.

Moving Validation, Html Helpers to Service Layer in MVC

We have two WebApplication in one MVC solution, one for Desktop and the other for Mobile version.
The architecture looks like this:
Model Libraray ( including repository and DB Model )
Service Layer ( Business Logic )
Web application Project ( views , controller, viewModels for desktop )
Mobile web project ( Mobile views, controller, viewModel)
I added a service layer into this project http://www.asp.net/mvc/tutorials/validating-with-a-service-layer-cs).
as long as these two web projects have different controller but most common logic , which of following I can move to service layer.
HTML Helper classes
View Model validations
Common functions
Thanks in advance.
First to answer your question of where to position those codes
View Model validations
If there is no particular reason to use the service layer model validation I'd rather advise you to do model validation using data annotations within Model library. All you have to do is to add some attributes to your entities' properties and things will work out of the box including validation messages (if you add validation elements using Html.ValidationMessageFor() or similar) in your client side view.
HTML Helper classes
HTML Helper classes should be part of Common UI library if they're supposed to be shared. They don't belong in any of the existing layers, because all of them are presentation layer (web apps) independent. I suppose your HTML helpers will be presentation layer dependent hence a separate library would suffice.
Common functions
Depending on where you need to use common functions, they may as well be part of Model library or Service layer.
How I structure my web apps
The following are written as layers. They're of course separate projects in the whole solution so they become separate assemblies.
Objects layer - contains all common classes/enums/interfaces, general functionality and application model POCOs used by any layer; that's why it's referenced by all other layers
Data layer - has data access objects (that may as well be inherited from POCOs in the Objects layer) that are only used within this layer and perform mapping to and from application layer POCOs; There are also repositories in this layer hence this layer/assembly is referenced by the next layer (service)
Services layer - contain business logic and manipulate application model classes; gets data from presentation layer and uses Data layer to manipulate data in the backing store (wherever it may be - this is of course part of Data layer repository to communicate with the store)
Presentation layer - may be a web application or anything else; references Objects and Services layer so it's able to communicate; any objects that are presentation layer only are also created here (special view models required by views but not by services);
All these mean that my Objects layer provides means of communication between layers by providing common classes that are used to exchange data between layers.
In cases where there are certain other providers I need to implement they may be part of a separate layer, but upper layering works for the 90% of all applications. A good example would be some common library that gets reused across different applications. Depending on what that library provides it gets referenced by those layers/assemblies that need its functionality.
In you case where you have two web applications, I would create a special layer named Presentation where all common HTML functionality would be and then reference it in both web applications.

Domain Entities, DTO, and View Models

I have an ASP.NET MVC 2 application with a POCO domain model and an NHibernate repository layer. My domain model has no awareness of my viewmodels so I use automapper to go from viewmodel to entity and vice/versa.
When I introduced WCF to my project (a late requirement), I started having to deal with disconnected objects. That is, I retrieve an entity from the database with NHibernate and once that entity is serialized it becomes disconnected and each child collection is loaded regardless of whether or not I plan on using it meaning I'm doing alot of unnecessary database work.
After reading up on this, I see that it is highly recommended that you not expose your entities outside of your domain project and you should instead use DTOs.
I see the reason for this but I'm having trouble figuring out how to implement it.
Do I map from viewmodel to DTO in ASP.NET MVC, send DTOs through the service layer, and map from DTO to entity in the service layer? Where should I define my DTOs?
I like to have my service layer keep entities encapsulated within it, and return/receive only DTOs. I keep the service contracts as well as the DTO's in a separate assembly which both the MVC project and the Service implementation reference.
Inside the service call implementation, the service maps dto's to entities, then does the interaction with repositories and other entities as it needs to.
On the app/mvc project I sometimes will get lazy and just use DTO's as the models for certain actions (especially CRUDy ones). If i need a projection or something like that, then I'll make a viewmodel and convert between DTO and viewmodel with automapper etc.
How exposed your entities are is a subject of much debate. Some people will push them all the way to the view/app layer. I prefer to keep them in the service layer. I find that when the entities leave the service layer, you find yourself doing business logic type stuff anywhere where they're interacted with, stuff that should probably reside in a service.
I treat my DTOs like ViewModels because the UI layer ( MVC app ) is requesting them. You could go Entity -> DTO -> ViewModel but I think thats over engineering if the only consumer of your service is an MVC application. If somehow the DTOs will actually be used for data and not simply screen specifications then you should probably use additional mapping.
I've also simply returned entities from my WCF layer and let the automatically generated proxy objects on the client be the DTO. The entities almost become DTOs because of the proxy classes and no business logic comes over to the client.
And of course, this is all "It Depends" what your architectural goals are. This question is borderline subjective and argumentative IMHO.
I like defining the DTO in the MVC project and then creating extension methods to transform from domain entity to DTO (and vice-versa).
The transformation would take place in the mvc functions.
I just wrote a post about a way of getting around all this DTO <-> DO transformation. Maybe you check it out http://codeblock.engio.net/?p=17

Resources