Building an ASP.NET MVC4 Application with EF and WebAPI

ASP.NET MVC has come a long way since "The Gu" jotted down some ideas during an airplane ride to a conference in 2007. In just under four years, ASP.NET MVC has seen its fourth release, and it provides developers an environment that eases development, streamlines processes, and promotes modern patterns.


Dive In

Jumping right in is one of the best ways to get a handle of new technology. Let's go ahead and dive right into teh codez!

Setup

I will be using Visual Studio 2012 Release Candidate, which is available here. I also recommend downloading SQL Server 2012 because the new Management Studio is a much needed improvement over earlier versions.

Once VS 2012 is up and running, go ahead and create a new project. Go to File -> New Project and choose an Internet Application. It's not a perfect template, but it'll get the job done.

Project Options

Note: the code for this demo application is located in a Github repo. I won't go through every single piece of code in this app, but you'll have a good understanding of an MVC4 application at the end of this tutorial.

Entity Framework

I am going to use Entity Framework (EF) Code First for the data model. EF Code First lets us generate database tables with nothing more than a few Plain Old CLR Objects (POCO). Plus, EF lets us use LINQ to Entities and Lambda expressions, making it easy to query and issue commands. A win win!

Our application will be a review site for reviewing... stuff. Therefore, the data model needs to incorporate all the necessary bits and pieces for a single review. We'll start with a class called Review. Write the following class in its own file in the Models directory:

The Review class has it's Id (the primary key), the Content property to store the review, a Topic such as a restaurant name (or any name of an organization), an Email property, and an IsAnonymous flag to signify if the reviewer is anonymous. The CategoryId and the Category properties create a foreign key relationship to tie a review to a Category (eg: Doctors, Dentists, etc). And last is a collection of Comment objects.

Now write the Comment class. Once again, add the new class to the Models directory:

The comment class has an Id property for the primary key, Content of the comment, an Email property, and an IsAnonymous flag for users. Then there are ReviewId and Review properties to create a foreign key relationship between comments and reviews.

Last is the Category class. Here is its code:

This class is self-explanatory.

You probably noticed extensive use of the [Required] data annotation in the above classes. These designate a non-nullable field in the database and provide validation later down the road. You can also create your own custom validation attributes if you so desire. In addition to [Required], we also used the virtual keyword for some properties; those properties signify foreign key relationships with other tables.

To create the corresponding tables for these classes, you'll need to create a DbContext class. The following code creates a context class called ReviewedContext:

EF Code First lets us generate database tables with nothing more than a few Plain Old CLR Objects (POCO).

Every property in this class corresponds to a table when generating the database. The Configuration.ProxyCreationEnabled = false; makes sure that the entities are retrieved as objects of their respective classes instead of proxies--making debugging much easier.

Next, we set up a database initializer. An initializer ensures that the database is created correctly when the data model undergoes any change. Without an initializer, you'll have to manually delete the database if you make a change to one of your POCOs. There are a few different types of initializers to choose from: DropCreateDatabaseAlways and DropCreateDatabaseIfModelChanges. The names are self explanatory. The one we are going to use is DropCreateDatabaseIfModelChanges.

The DropCreateDatabaseAlways and DropCreateDatabaseIfModelChanges initializers have a side effect: they drop the tables (and thus data) in the database when the model structure changes. But EF Code First provides a third way to generate databases: Migrations. This new feature tracks changes to the database and does not lose data as the POCO classes change.

Here's the code for our initializer:

The ReviewedContextInitializer class overrides the Seed() method. This gives us the ability to fill our database with some test data. Now, we need to visit the Global.asax file and add the following line to the Application_Start() method:

Let's create some repositories for retrieving data from the database, and we'll go ahead and setup dependency injection (DI) with Ninject. If you don't exactly know what DI or Inversion of Control (IoC) are, then take a moment to read this article.

Basically, the idea of dependency injection is to inject a concrete dependency into a class, as opposed to hard coding the class to be dependent upon the concrete dependency. In other words, it's a decoupling of one concrete class from another. If that's still clear as mud, let's look at a brief example:

This code creates a class called Foo. It is dependent upon the functionality of an object of type Bar, and the Bar object is created within the Foo class. This can be difficult to maintain and unit test because:

  • Foo and Bar are tightly coupled. As a result, maintenance is less than ideal.
  • Foo is dependent upon a specific implementation of Bar, making unit testing difficult.

This code can be improved upon with just a few modifications. Take a look at the revised Foo class:

In just under four years, ASP.NET MVC has seen its fourth release...

Now, the Foo class is not dependent upon a specific implementation of Bar. Instead, an object of a class implementing the IBar interface is supplied to Foo via the latter's constructor. This approach greatly improves maintainability, while also allowing us to inject any IBar object--making it easier to unit test our code.

With that brief description out of the way, let's get Ninject up and running. Fire up the Package Manager Console and run Install-Package Ninject.MVC3. This will add Ninject to our project.

The first repository we'll create is the ReviewsRepository, and it will implement the IReviewRepository interface. Here's the interface:

This interface ensures that our review repositories provide the basic CRUD operations. We also get the utility of retrieving reviews by a specific category, as well as retrieving the comments for a given review. Now let's write a concrete class implementing this interface:

WebAPI is a MVC-like framework that we can use to easily create a RESTful API...

This repository relies on a ReviewedContext object that is stored as a class variable. This enables us to use LINQ in any of the repository's methods, making database interaction easy.

WebAPI has a nice feature that lets us add our own DI framework. This feature is beyond the scope of this tutorial, so be sure to read this article to help get that setup.

One of the most important locations for our code is the App_Start folder, which contains a file called NinjectCommonWeb.cs (installing Ninject automatically adds this file to App_Start). This file contains a static class called NinjectWebCommon, and it has a method called RegisterServices(). In this method, add the following code:

The first three statements bind an interface to a concrete implementation of the interface, and the fourth line sets up the DI for WebAPI (the feature covered in the aforementioned article).

WebAPI

Let's now create the controllers for the API. WebAPI is a MVC-like framework that we can use to easily create a RESTful service, and it can run inside of a MVC4 application, in its own project, or it can be self hosted outside of IIS. But that's not all; it has many other features, such as: content negotiation (to automatically serialize it data into whatever format is requested), model binding, validation, and many more.

We first need to create an endpoint with WebAPI, and we do that by creating a class that inherits ApiController. Getting started with this is rather easy. Visual Studio 2012 has a new feature that creates a new, partially scaffolded controller.

Create ApiController

This will create a controller class with a few methods already defined for you. Here is an example:

The method names correspond to the HTTP verb they represent. We'll now create the ReviewsController class. The code a bit long, but pretty straightforward.

This code uses IReviewRepository and ICategoriesRepository objects to perform the appropriate action (eg: retrieving data for GET requests, adding data with POST requests, etc). These respositories are injected with Ninject via Constructor Injection.

If you don't have Fiddler yet, get it now--even if you're not a .NET developer.

Notice that some of the methods return different data types. WebAPI gives us the ability to return a non-string data type (such as IEnumerable<Review>), and it will serialize the object to send in the server's response. You can also use the new HttpResonseMessage class to returning a specific HTTP status code along with the returned data. One way to create an HttpResponseMessage object is by calling Request.CreateResponse(responseCode, data).

We can properly test our WebAPI project with a tool such as Fiddler2. If you don't have Fiddler yet, get it now--even if you're not a .NET developer. Fiddler is a fantastic HTTP debugging tool. Once you're running Fiddler, click on RequestBuilder and enter the API URL you want to test. Then choose the appropriate request type. If making a POST request, be sure and specify a Content-Type: application/json header, and then place a valid JSON structure into the request body. The following image demonstrates a raw JSON POST request to the api/reviews URL:

When you send the request, you'll see something like the following image:

Notice the POST request's status code is a 201. WebAPI does a great job of returning the correct status code for a RESTfull web service. Have fun with Fiddler2, it's a fantastic tool!

With WebAPI, you can specify the routing for the controllers (just like MVC). In MVC4, a RouteConfig.cs file is added to the App_Start folder. Routes for a WebAPI project are just like MVC routes.

The DefaultApi route is automatically generated by Visual Studio. The other two routes are custom and map to specific methods on the Reviews controller. There are many articles and tutorials that provide good information on routing. Be sure to check this one out.

MVC4

That covers a lot of what WebAPI has to offer. Next, we'll write a few methods to display the data. We'll consume the API in a little bit, but for now we'll use the repositories in our HomeController. A HomeController was created by Visual Studio; let's just modify its methods to display the data. First, let's get a list of the categories in the Index method.

Here, we continue to use DI by accepting the repositories as parameters for the HomeController constructor. Ninject automatically inject the appropriate concrete classes for us. Next, let's add some code to the Index view to display the categories:

This generates a list of categories that users can click on. Now add a new method to HomeController that retrieves a Review. We'll call this method Reviews, shown here:

Because a route already exists for /{controller}/{action}/{id}, you can use a URL such as Home/Reviews/Doctors. The routing engine will pass "Doctors" as the id parameter to the Reviews method. We use the id as the category and retrieve all reviews associated with that category. If no category is provided, however, we simple retrieve all reviews in the database. Once we have all the reviews, we pass the review list to the view. Let's look at the view right now:

This code uses a new feature of MVC4. The <ul/> element's class attribute will not appear in the HTML if hasComments is null. Read more about this feature here.

JavaScript

No modern web app is complete without JavaScript, and we'll use it to consume our WebAPI service. We'll use Backbone.js for this; so, ahead on over and download Backbone and its dependency Underscore. Place the JavaScript files in the Scripts directory.

We'll take advantage of another new MVC4 feature called script bundling. In the App_Start folder, you'll find the BundleConfig.cs file. In this file, you can configure MVC4 to bundle JavaScript files together. Open it up and add a new bundle, like this:

Then in the /Views/Shared/_Layout.cshtml file, add the following at the bottom of the page's body:

This will bundle your scripts if your application is in debug mode, or leave them alone with it turned off.

The MVC4 code we wrote for retrieving the review list is a fine way of displaying them, but all the new hawtness is using Ajax. So let's refactor the code to use Backbone.js. Through JavaScript, we'll retrieve the views asynchronously after the page has loaded. Create a new file in the Scripts folder called home.js. Add the following code to that file:

These are the JavaScript data models, each corresponding to a URL to retrieve data from the WebAPI service. Now let's write the view:

This view is for the entire list of reviews. When the collection's fetch() method is called, it triggers the reset event and then calls render(). The third parameter passed to the on() method is the scope, or what this will be in the render() callback. In the render() method, call the collection's each() method, passing the renderItem() method. The renderItem() method will be called on each item in the collection, generating a new ReviewItem for every review.

The code for ReviewItem follows:

WebAPI is a fantastic addition to the ASP.NET stack; a feature rich REST based API has never been easier.

The ReviewItem view is responsible for rendering each individual review. The initialize() method compiles the template used to display each review; this template resides in a <script/> element. Backbone pulls the template out of the <script/> element and combines it with the review.

A click event handler is also set up for loading the comments for each review. When the link is clicked, the getComments() method is called, fetching the comments by passing an Id to the WebAPI service. The fetch() method is merely an abstraction to jQuery's $.ajax method, so normal Ajax parameters, like data, can be passed in the fetch() call. Lastly, the loadComments() method will fire and create a new CommentItem view for each comment returned. The tagName on this view ensures the view is created with an <li/> as its $el property.

Next, let's look at the CommentItem view:

This is a simple view that renders each comment. Now let's modify the Review.cshtml view as follows:

Notice the @section scripts in the above code. This is not a new feature to MVC4, but it is a great tool to render specific pieces of JavaScript. In the _layout.cshtml file, there's also a @RenderSection("scripts", required: false) which renders the section defined in the view. The <script/> elements are Underscore templates to render content. They follow a Ruby-esque syntax, and anything inside <% %> is evaluated as a statement. Anything inside of <%= %> will output to the HTML. Loops and conditional statements can be used like this:

That's the template. To use it, do this:

There are many JavaScript templating frameworks available on the Web: Handlebars.js, mustache.js, and Hogan.js are quite popular. Be sure and check them out and pick the one that works for you.

Conclusion

WebAPI is a fantastic addition to the ASP.NET stack; a feature rich REST based API has never been easier. There are a lot of great new features in MVC4. Be sure and check them out! As I previously mentioned, the code for this example is available on Github. Fork it!

Tags:

Comments

Related Articles