ASP.NET MVC - Model can have business logic? - asp.net-mvc

I read a couple of articles which defines domain model (as in MVC) as something that holds business logic. I never considered a model to hold any methods other than the model properties.
I would like to know if actually there is a thought which supports having functions and business logic in the domain models.
Thanks in advance.

Of course business logic should be inside domain models. But, domain models are more than just entity framework entities. Domain models consists of many small classes which reflects business domain.
In my typical MVC application, I usually split some type of business logic into these (but not limited to):
ViewModels which responsible for model for view.
Controllers which is thin and responsible for application flow.
Simple business logic such as required field can exist as attribute within entity framework model or ViewModels.
Complex business logic such as place order, booking ticket are promoted to be its own class such as PlaceOrderOperation or PlaceOrderCommand.
Simple query logic might be inside the Controller or short extension method to DbSet<Entity> type.
Complex Query also promoted to its own class such as GetMostPorpularProductsQuery assuming that the query is complex.
Infrastructure components may be extension to Entity Framework or MVC components such as ActionFilter, CustomRoute, CustomTemplate or its own classes such as EncyptionHelpers etc.
Conclusion
Building domain Model is more than just creating classes prefix with BusinessLogic such as UserBusinessLogic or with Services such as UserServices. It should consists of many small classes which responsible for one thing. Of course, you would require some usage of design patterns, choice of frameworks, infrastructure components such as error handling, localization, caching, etc.
Welcome to the trade-off world. :)

An MVC Model can indeed have business logic. MVC responsibilities been discussed in more depth here and here is a discussion on anemic domain models - this might help clear things up for you?
From MSDN:
Models, which is provided for classes that represent the application
model for your MVC Web application. This folder usually includes code
that defines objects and that defines the logic for interaction with
the data store. Typically, the actual model objects will be in
separate class libraries. However, when you create a new application,
you might put classes here and then move them into separate class
libraries at a later point in the development cycle.
What might be confusing the issue is that many ASP.Net MVC implementations use View Models, which are classes used to transfer presentation tier data between View and Controller.
In a typical large project setup, we usually delete the Models folder, and instead move our EF data layer, Entities, and business / service logic into separate assemblies entirely.

Based on my experience best place to place business logic is layer between controllers and models. Try some popular patterns, like repository or tasks/commands.

Related

MVC project setup at the enterprise level. What's expected?

By reading at several articles posted here, I get mismatched information about how to properly configure a project.
I am looking for advise about how the pros do it at the enterprise level.
I see different schools of though about this, some people design in a truly N-Tier fashion, others prefer to use EF Code First directly in the MVC application and have FAT models and sort of have one big MVC app with logical separation of concerns, etc.
So for a mid-size project this is my set up and I want to ask for your opinions about it.
MVC application
Models -- Here my models have just what the view needs, validation logic, etc. These models are designed to pass data between the controller and views only.
Controllers -- Call the service layer where business logic lives and gets domain models back if needed. Converts domain models into view models and vice-versa.
Service layer
This is were the business (domain) logic lives.
The service layer is also in charge of communicating with the data layer to perform CRUD operations.
The service layer returns domain models to the controller in the MVC application and also expects domain models when invoked.
Data Repository layer
The data layer is a thin wrapper around EF and performs CRUD operations.
usually I will have a Code First approach where entity models are created for me by EF.
I convert the EF code first models to domain models and return these to the service layer.
The data layer also expect domain models from the service layer that in turn I convert to EF code first models and persist to the DB.
Domain Model layer
These are the domain models that are used and shared thorough the applications layers.
What's best design?
What's expected at the enterprise level?
There's nothing particularly wrong with the approach you've laid out. However, I do see it as overly complex. Your repository layer, in particular, is a totally unnecessary level of abstraction. You could simply just roll the EF stuff into your service layer and call it a day. Having to convert the entity into a domain model and then to a view model, is frankly, a pain. Just map your entity to your view model and back.
The only thing you should really bear in mind is that ASP.NET MVC very loosely follows the MVC pattern. There's no such thing as a true MVC Model, and trying to force something like an entity class into that mold is a huge mistake. Your Model is the combination and interaction of your entity class, view models that represent that class, and the querying logic you tuck away in your service layer.
I would like you to suggest have these layers in your project ----
Entites Layer--
it should contains only all your poco classes in a model folder.Nothing else
Data Layer----
It should contain Db interactions logic.
Also your Dbcontext class should reside in this.
You may use Repository Pattern and unit of work pattern for better seperation of concern.Use dependency injection to resolve dependencies using Unity Container(there are many other container also available).Please have a look on these design pattern and container.there are many articles available on net for this.Simply go through them thoroughly.
Service Layer ----
It should contain only service methods to call into your controller as your controller should not directly talk to data Layer.Its a much better approach and prevent your business logic from being exposed to external attacks.
MVC Layer or UI layer ---
It should contain only the controllers whose work is to call services and business logics inside them.
and View folder where we have all the views to be shown to the end users.
Its a pretty big question.I hope may be u get some idea from this.

ASP.NET MVC vs. nTier Separation of Concerns

with nTier architecture it is common to create a data, business, workflow and ui layer. In this setup, your data layer and business layers are separated and can be reused by other layers.
In ASP.NET MVC it seems that the model is acting as both the business and data layer as clearly the model is the data and all documentation indicates that business logic belongs in the model.
How is this architecture promoting good separation of concerns when these two layers are mixed?
There is a difference between View Models and Domain Models. Domain Models is your application domain. These models can be used everywhere, in any tier and they are usually placed in a separate shared project. Your View Models are just for the UI. They are dependent on your page needs/structure. Let's say you want to create user management page, than your view model may be a class with 2 properties User and List<Role> where User and Role are domain models.
And finally, your Data Models usually are just database transfer objects. Entity Framework models are usually used as Data and Domain models at the same time.
So, answering your question: you choose your comfortable level of mixing models by yourself. The problem is if you don't want to mix, then you will have quite a bit of model duplications across the solution and you will have to do mapping from one type of model to the other manually or with help of libraries like AutoMapper. That's why developers choose some compromise.
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. (Wikipedia)
We should take into account that when we talk about ASP.NET MVC, we are talking about "User Interface" so, it is a user interface framework not an application one. In MVC, concerns are separated in three components: Model, View and Controller.
In multi-layer or multi-tier architecture, concerns are mostly separated in Presentation, Application, Business and Data access layers which is an application framework architecture and ASP.NET MVC belongs to the Presentation layer.
All in all, separation of concern is completely achieved if we distinguish between Application and Presentation frameworks.
Andrei M is spot on. I agree with the difference between View models and domain models. It may help to think of the M in MVC as a model for your views, and these "view models" should not have any knowledge of where they get their data from. Therein lies the separation of concerns. A controller will broker the exchanges necessary between your domain model and your view models to populate the view models with data. These data exchanges that the controller brokers are often achieved by using another layer such as a repository, infrastructure, or service layer... but not necessarily. In a one-project solution, your "Models" folder might contain a domain model, and then you might have a separate folder called "ViewModels". A controller would fetch data via "the Model" and then populate the view model with the data it "received" from the model. The view model would be the underlying model for your strongly-typed view. One may wonder why a developer might even bother with using a view model if there is a simple one-to-one mapping between domain object and a view. One example is that you may need to "flatten" a domain object and its relationships. Another example might be that for an index or list page, you may need to include search filter; view models greatly simplify accommodating changes to requirements.

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.

Is it a good aproach to make a difference between domain models and MVC models?

(I am a very beginner in MVC)
I mean to have a business logic layer with the domain models and an application service layer with view models and controllers obtaining view models only from application service methods. Controllers doesn't contain any logic and the MVC models are the view models (from the app service layer) which contains logic only related to displaying.
Any tutorial I have seen on ASP.NET MVC focuses on having logic in controller classes, but I think in this way (in a large app) you can duplicate business logic, writing redundant code.
Is it a good approach to make a difference between domain models and MVC models
Definitely, I always separate my domain models from my view models because, like you, I agree that domain models don't belong in the controllers.
Controllers in an ASP.NET MVC project are effectively view controllers and as such shouldn't really contain business logic. Using a service layer is generally the best way to manage communication between your presentation / business layers (like you appear to be doing anyway).
Yep, its a good idea to keep them separate. The way I've seen it done is that you have your "Business Objects" namespace, then your 'View Models' namespace. The objects in the 'View Models' namespace are the Models for MVC and usually contain a mix of regular types and instances of business objects.

How can I extend the Model in ASP.NET MVC and Entity Framework?

In my first ASP.NET MVC applications, the model was a simple O/R mapping between a table and the classes, managed by the Entity Framework.
Now I would like to add some meat to this skeleton, and introduce business methods for the generated classes. What is the recommended approch to this in ASP.NET MVC (with Entity Framework)? My favorite would be solution which also can be used in a service layer, with no ASP.NET MVC references, so that the same domain logic also could be reused in a desktop client.
Technically, I think it should be possible to extend the generated classes in a way which preserves the additional business logic even if the O/R classes need to be refreshed. (This is more a question related to the Entity Framework however.)
Edit: Many thanks for the contributions, and the information about the next version of Entity Framework (4.0). Building two sets of classes, one auto-generated to represent the data in the persistency layer and one for the actual business logic sounds interesting.
Within MVC.Net, the model is the least clearly defined part. In my opinion, it's basically the rest of your application (i.e. anything not related to the View or the Controller). The O/R Mapping part of your application should probably be outside of the "Model" also, as this is more of a data layer. The Model, should really deal in business objects and create views of your data to pass to the View.
There are lots of differing opinions on this, but I think it's best not to think of MVC.Net as traditional MVC Architecture.
If you are using EF v1.0 right now, the Entity Framework is very intrusive into your application, which means that you cannot create POCO very easily. The way you can extend your model is by using the partial class. So when you refresh your model, the partial class you did will still be valid. The Entity Framework team realizes this is a problem , and have improved this in next version (EF V4.0).
NHibernate is much more friendly and allow you easily extend your business logic.
I really think this blog post by Jeremy D. Miller is very good at pointing out the problem.
Abstract your Business Layer out into another project, then pass an instance of it onto your mvc controller using something like structure map. You can then call this Business Layer from your controller to retrieve your business entities (Model) and pass them on to the UI. This will allow you to resuse your Business Layer in your desktop application.
Not only meat but also some clothes and a style could be added to this project to make it seem chic. It depends on the time you have for the project. If you have time, I could suggest you to get a look to TDD and the frameworks that could be used with TDD such as Castle, NUnit, Moq etc.
As you mentioned a service layer is a must for any project but with these kinds of frameworks you could design your architecture more robust.

Resources