How to model a Database View in ASP.NET MVC - asp.net-mvc-3

I have to gradually replace an ASP.NET Web Forms application with an ASP.NET MVC3 layered application. Let's take into consideration just the Repository layer.
In my new MVC application I have one project for Data (name MVC.Data) and one for Web.
In the MVC.Data I have an edmx file with the EF classes, which models just the DB table (no views), and a Respository class myRepository which provides methods that perform simple queries.
In the old Web Forms application I have a GridView which is filled using as DataSource an SQL database view.
In order to have the same result in my new MVC3 application, I have two options:
1) Create a Service layer (and project MVC.Services), where I have a method that fill a new class myViewClass which contains all the fields of the SQL DB view and give it to the controller.
2) Create a class within the MVC.Data project which is directly filled by its constructor by using LINQ statements directly against the EF classes.
I read about the factory pattern and the 1st solution seems the most appropriate, however many people always suggest not to create a Service Layer if it is not needed. What is the best choice in this case?

Actually building the view model should be done in a mapping layer. Basically your controller action might look like this:
public ActionResult Index()
{
SomeDomainModel model = repository.GetSomeDomainModel();
SomeViewModel vm = Mapper.Map<SomeDomainModel, SomeViewModel>(model);
return View(vm);
}
The view model is defined in the MVC project as it is a class that is specifically designed to meet the requirements of the given view.
The Mapper.Map<TSource, TDest> method I have shown in my answer comes from AutoMapper which I use in my project but you could define any custom mapping layer you like.
The mapping layer must also be part of the MVC project as it must be aware of both your domain models and your view models in order to perform the mapping.
As far as the service layer is concerned, you could use one when you have some complex business operations which could be composed of multiple simple repository calls. But some might argue for the existence of a service layer at all. I think that both approaches have their pros and cons that must be evaluated when designing a system and most importantly take into consideration the specific context and scenario you are designing.

Related

how to combine strategy and mvc pattern

I'm trying to made my project class diagram diagram. In my project, text contents are converted to visuals, i had used strategy and factory pattern for visuals, but currently i'm using php code igniter at server end and i'm not very much aware of mvc pattern in class diagram. so my question is how can i combine them?
Edit: IVisual is used here for strategic pattern (TimeLine, GeoLocation, Relationship sheet are all strategies), and VisualFactory is used as factory class which creates any type of visual.
MVC is designed to separate your concerns between your model(data), your view(html rendered) and your controller (the request/response engine, in your case php controllers).
Your view will contain all the classes that carry your data, for example you will need one or many classes that carry the geolocation of Country XYZ is Latitude:XX and Longitude:YY
Your controller is simply the gateway between your model and your view. for example, the controller will receive a request to http://myapp.com/page1, then the controller connects with the database, brings a model with it and passes it to the view, then the view will recognize that you need to represent the geolocation data and will render the html.
MVC is in a higher hierarchy of software design, usually is embedded in the framework that you use
hope it helps,

Need expert's voice for mvc beginner about Controller & Model

I am quite new to MVC. I am having the following questions, please help me clarify those questions, thanks a lot.
Q1. Where should I populate my view model? e.g. My view model is very big, and contains a lot of the dropdown listbox, multi select list and the other few complex objects. I am currently populate them inside the view model self, by passing the model through the constructor, and load all the object data within the constructor. I also see my college populate the viewmodel inside controller. so I am confusing now, coz lots of people suggest to keep the controller small and skinny.
Q2. We are using the linq2sql as data access layer, should I use the table entity in my viewmodel instead of creating separate model class? Expert said it's bad, but if create seperate model class, I basically repeat them and I also need to copy those value to linq 2sql entity every time when I want to persist data, it's not that fun, too much work.
lots of people suggest to keep the controller small and skinny.
Yes. What people mean is that the controller should not contain any logic, except for model <-> view mapping. With model I mean the "M" in MVC.
Q2. We are using the linq2sql as data access layer, should I use the table entity in my viewmodel instead of creating separate model class? Expert said it's bad, but if create seperate model class, I basically repeat them and I also need to copy those value to linq 2sql entity every time when I want to persist data, it's not that fun, too much work.
No. You should not. Read my answer here: ASP.NET MVC Where to put custom validation attributes
Use a mapping framework for the model -> viewmodel conversion.
Update:
From what I understand, you suggest to assembly the viewmodel inside the controller (I mean call the business layer or repository to get my data) and use controller to call the business logic dealing with the data, am I right?
yes. The controller is really a glue between your business layer / repositories and your views. The views (and view models) should know nothing about them and the business layer / repositories should know nothing about the controller/view.
The controller was created for just that purpose. To create an abstraction between the user interface layer and the lower layers. Hence the only code that should exist in the controller is to make that possible (and therefore following the Single Responsibility Principle)
If you start adding that logic into your view models you start to add coupling between the lower layers and the user interface layer. Doing any changes in the lower layers will therefore also affect all your view models (instead of just the controller
your viewmodel should be a poco, and should most certainly not be handling the mapping of the model. if you don't want to map your model to your viewmodel in the controller i would suggest you look at something like automapper. it makes it easy.
once you've mapped from your model to your viewmodel, any extra properties that need to be set such as your lists should be set in the controller.
as i stated previously, definitely don't tie your viewmodel to your current orm or table structure. you never know what might need to be refactored, and if you can handle it via an automapper mapping instead of changing your view and viewmodel then you've saved yourself a significant amount of time.

ASP.NET MVC: Where do you assemble the view model for a view?

From inside to outside, these are our MVC app layers:
MS SQL / Tables / Views / Stored Procs
Entity Framework 4.1 (ORM) with POCO generation
Repository
Service (retrieve) and Control Functions (Save)
Routing -> Controller -> Razor View
(client) JQuery Ajax with Knockout.js (MVVM)
Everything is fine until I need to create a single ViewModel for step 5 to feed both the Razor view as well as the JSON/Knockout ViewModel:
Header that includes all Drop down list options and choices for the fields below
Items - an array of whatever we send to the client that becomes the ViewModel
Since the Controller won't have access to the Repository directly, does this mean I create a service for each and every view that allows editing content? I'll need to get the POCO from the repository plus all options for each field type as needed.
It just seems redundant to create separate services for each view. For example, a viewModel to edit an address and a separate viewModel to edit a real estate property that also has an address. We could have a dozen forms that edit the same address POCO.
To make this question easier to answer, is allowing the Controller direct access to the repositories a leaky abstraction?
Well, so are your controllers going to have code that translates POCOs from Entity Framework into separate view model objects?
If so, then you should move that code to a separate class, and follow the single-responsibility principle. Whether that class is in the "service layer" or not is up to you. And whether you use AutoMapper or not is up to you. But these kind of data mappers should not be part of the controller logic; controllers should be as dumb as possible.
OK, now let's ignore the data mapping problem, and pretend you could always use your POCOs directly as view models. Then you would still want a service layer, because it would translate between
userService.GetByUserName("bob")
in your dumb controller, and implement that in a specific manner by returning
userRepository.Users.Single(u => u.UserName == "bob")
Putting these together, your UserController ends up taking in IUserService and IUserDataMapper dependencies, and the code is super-dumb, as desired:
public ActionResult ShowUserPage(string userName)
{
var user = userService.GetByUserName(userName);
var viewModel = userDataMapper.MakeViewModel(user);
return View(viewModel);
}
You can now test the controller with stubs for both dependencies, or stub out IUserDataMapper while you mock IUserService, or vice-versa. Your controller has very little logic, and has only one axis of change. The same can be said for the user data-mapper class and the user service class.
I was reading an article this morning that you might find somewhat illuminating on these architectural matters. It is, somewhat condescendingly, titled "Software Development Fundamentals, Part 2: Layered Architecture." You probably won't be able to switch from a database application model to the persistent-ignorant model the article describes and suggests. But it might point you in the right direction.
i personally always inject the repository/repositories into the controller. i'm not sure why you would want to have a service layer between the repository and the controller. if anything you would use specifications.
once you've done that, check out automapper. its a mapper that, once properly configured, can map your domain model to your viewmodel, and back again.

MVC using existing data- and businesslayer

I have an existing application with a datalayer (primary EF4), a businesslayer (custom code) and a windows application - now I want to create a webapplication using ASP.NET MVC but I am not sure exactly what to do especially in my models.
When my data and business logic already exist how should I structure my Models and Controllers compared to a referenceproject like MVC Music Store v2.0 (http://mvcmusicstore.codeplex.com/)? All my entities are stored in my datalayer and all my methods and logic are stored in my businesslayer so I guess I need no Models (unless I need specific web Models) and I guess my controllers will only need to call the methods in my businesslayer as I would to in a normal webform application?
Another question, if I need to display 2 lists with data from 2 different entities on 1 page I guess I need to create af Model with 2 properties (one for each entity)?
The last one for now, if, for some reason, e.g. a Get method from my businesslayer returns an exception how should this be handled in my Controller/View?
It depends on the complexity of your application. I would at the very least introduce ViewModels for each view so you can supply the view with the data that is required. If your application is light weight it might be fine to use your business layer in the controller. However, you might want to introduce a service layer that interacts with your business layer just to keep the controllers thin.
As for exception handling, you might want to look into the HandleError attribute.

In a MVC tiered architecture a Repository class is part of the Business layer or not?

suppose you have an MVC application with the Model represented by an Entity Framework (EF) that "gets" data from a database and the action methods of the Controller that implements all the business logic. The Controller gets data from the database through the EF.
Imagine that now you create a Repository class that is placed between Controller and Model. This way you have:
1) Controller: implements most of the business logic;
2) A Repository class, responsible to implement simple business logic, provide data to every Controller in the application through methods and get data from the EF;
3) Model: EF classes that gets data from the database and provide them to the Repository class.
Is the Repository class the business service layer or there is the need to add a business layer placed between controllers and repository? In this latter situation we have:
1) Controllers: implements just the request elaboration;
2) Business layer: a set of classes responsible to implement most of the business logic and provide data to every Controller in the application through methods;
3) A Repository class: gets data from the EF and expose methods to the Business layer for querying the database;
4) Model: EF classes that "get" data from the database and provide them to the Repository class.
I do not consider the View because it is not relevant. I hope somebody can make clear for me this distinction. Many thanks
Cheers
Francesco
The definitions you have proposed for Model and Controller differ from the traditional usages of the terms in the MVC pattern - or at least, the pattern as defined by Martin Fowler here.
Usually it is the Model that contains most of the business logic, and the Controller is responsible for managing the flow of information between the View and the Model. To quote from Fowler's article:
The controller's job is to take the
user's input and figure out what to do
with it.
Looking at your actual question with regard to where a Repository should be placed, it would be within the Model, but encapsulated away as part of your data access infrastructure (that is almost the very definition of what a Repository is).
So the Model becomes made up of two key parts - Domain objects which have expressive business logic, and service infrastructure that does things like accessing the data access layer. (Another common approach is to have the Model made up of services which don't really feature a rich domain model, but still this contains all business logic and data access).
One last thought is be careful about over thinking or abstracting this stuff - keep it as simple as possible and only introduce a new layer to your architecture when you are sure it will give value. For example - EF itself can perform the role of your Repository in most scenarios, so using it directly without the repository layer can remove an unnecessary abstraction.

Resources