If you have built sites with the ASP.NET Razor Web Pages framework, you might want to look at migrating them to ASP.NET MVC at some point. This tutorial is the second in a series of three that explores how you do that by taking a step by step approach to migrating the WebMatrix Bakery template site to ASP.NET MVC 5. Along the way, each of the core parts of MVC are discussed by way of an introduction to the framework. The tutorial is divided into three parts. The first part looked at the roles of the View and Controller. This part looks at the M in MVC, the Model. Specifically, it features data access and view models. The final part will cover model binding and form posting. A download (c. 24MB) featuring the completed application is available on GitHub.

The Model

In the first part of the tutorial, I mentioned that the Model is a catch-all area for server side logic. Server-side logic in the Bakery site covers a number of different activities (or "concerns", as they can be referred to). These include data access, validation and sending email. There are many ways to organise this type of code, and the approach that you adopt will be largely driven by your own preference. This migration will show how to move the data access code from using the WebMatrix Database helper over to using the Entity Framework instead.

You might ask whether you can stick with the Database helper in MVC, and the truth is that you can. However, if you want to continue writing SQL and using the dynamic results from queries, you should really question your reasons for moving to MVC. Ideally, you want as much of your application to be strongly typed as possible so that you can catch errors at compile time (while you are typing in Visual Studio) rather than at runtime. The Entity Framework delivers a strongly typed approach to data access and is the recommended way to work with data in ASP.NET.

Introducing Entity Framework to the Bakery application

All MVC applications created using the Visual Studio template include Entity Framework by default. However, they may not include the latest version of the framework so the first thing to do is to update it.

Next, making sure you have copied the Bakery.sdf database file from the original site to the App_Data folder of the MVC application, add the following connection string to the web.config file. Make sure you add this to the web.config in the root folder, not the one in the Views folder.

You need a class to represent a product from the database so that Entity Framework can map the result of a database query to C# code. Add a new Class file to the Models folder and name it Product.cs. Replace the default code with the following:

The properties of the Product class mirror the fields in the Products table in the database. Data Annotation attributes have been used to set the maximum length of the string fields. These attributes provide validation out-of-the-box, and are also used by Entity Framework Migrations to set the field length in the database. You can read more about EF migrations in one of my previous articles.

Namespaces: Visual Studio has automatically added a namespace statement to the Product class. The class has been placed in a namespace called Bakery.Models, which takes the form ProjectName.Folder. Namespaces are used to organise code. They disambiguate between classes with the same name in different areas of a project. You might decide to name a class Database, because that helps to define objects in your application. You might also need to use the WebMatrix.Data.Database class in the same scope as your Database class. You use the fully qualified name including the namespace so that it is clear which Database class you are referring to.

Create a folder in the root of the application and name it DataAccess. Add a new class file called BakeryContext.cs and replace the default code with the following:

This file is the DbContext for the Entity Framework. It takes the same name as the connection string you added earlier, and has one property: Products of type DbSet<Product>, representing the Products table in the database. Notice that the namespace takes after the folder you created. Although part of the Model, this file has not been placed in the Models folder. The contents of the Bakery.DataAccess namespace form the Data Access Layer of the application.

Adding a Service Layer

Now that the data access layer has been created, you could just instantiate a DbContext in the controller and use LINQ to query its DbSet<Product> to get data to send to Views. However, that would result on the controller having a dependency on the data access layer. In time, it will also lead to "code-bloat" in the controller as you start adding validation and other logic to your action methods. Your controller will end up looking like a collection of code blocks from your Web Pages site, which is not what you want. You won't actually be separating anything. What you will do instead is create a Service Layer. This will consist of a set of classes - roughly one per entity or activity - which will be responsible for talking to your data access layer (EF) and delivering data to the controller so that it can pass it on to the view. It will also accept data from your controller and do whatever it needs to with it. This could include creating new database records, updating existing ones or deleting them. In the case of the Bakery site, it will generate an email in response to an order being placed.

Create a new folder in the root of the application called Services.

Add a new class file to the Services folder called ProductService.cs and replace the default code with the following:

Interfaces are one of the key mechanisms for code separation. They introduce a level of loose coupling by allowing you to programme against an idea rather than a concrete implementation of that idea. The interface is the idea. It represents something that implements both a GetProducts method which returns a List<Product>, and a GetProduct method that returns a specific Product object based on the id value passed in. The ProductService class meets these expectations and is therefore a concrete representation of the interface. It is actually forced to meet the expectations set out by the interface as the ProductService class specifically implements the interface. You can have other classes implement the interface and they can be swapped in and out quite easily - especially if you use dependency injection. This is particularly useful if you want to implement unit testing. You can swap the ProductService with a TestProductService that implements the same interface with minimal changes to other code. Then when you run your tests, the TestProductService will be used instead of a class that hits the database - protecting the integrity of your data and speeding your tests up. Dependency injection is not used in this tutorial but you can learn more about it from an earlier article.

Now you have a service that returns a list of products and a single product. You can use the first of these methods to generate the data for the home page of the site, which features all the products. You can do this by making the highlighted changes to the HomeController

This is essentially the code from the Default.cshtml file in the Bakery template site. If you run the applciation now, you should see an identical result to the one you get when running the WebMatrix site. I don't know whether you noticed, but there was little to no Intellisense or code completion in the view. If you hover over any of the model properties, like ViewBag.Featured.Name, Intellisense only reveals that the data type is a dynamic expression which will be resolved at runtime.

ViewBag is a dynamic object, just like Page in Web Pages. It would be much better to get strong typing in views so that you can capture potential typing errors at compile time rather than runtime. That's what view models are for.

View Models

A view model is a class that serves as a container for data for a view. The home page view features two pieces of data - all products and a featured product. The following class represents the two pieces of data. The Featured property represents an item from the Products collection taken at random. It is possible to just pass the collection of products to the view and then to generate featured product there, but the recommended approach is to keep that kind of logic out of the view, which is why it's done in the view model instead.

The view features an @model statement at the top that specifies the data type of the view model being passed in to the view. Since the view is now strongly type, full Intellisense is available.

This approach helps to minimise runtime errors arising from typos, and makes the views and controller cleaner.

Summary

In this section, you have seen how to create view models to give you strong typing in your views, making development less error prone. You have also moved your data access away from the dynamic-based Database helper over to the Entity Framework with the same benefits as provided by view models. In the final section, you will combine view models and model binding to simplify the process of posting data to the server. You will also complete the implementation of the service layer with components for processing submitted orders.