ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part II

Last week we blogged the first part of a four-part recipe for an ASP.NET MVC3 RESTful application with Backbone.js. For the few of you who may have missed the post, it is a tutorial to get the popular Backbone’s Todo demo working with an ASP.NET MVC3 backend.
We started kneading our mix, setting up a Visual Studio 2010 project and adding to it Entity Framework 4 and generating the database. If you followed the first part, just keep reading, otherwise you can get back on track downloading the ASP.NET MVC3 Tutorial with Backbone.js – Part I.

This article and the following two will deal with the 3 parts of our Model-View-Controller web application respectively. Today we start with the core: it’s Model day!

The Model Layer

Given that we adopted ADO.NET as ORM framework with a “Model-First” approach, we don’t need to explicitly create a Todo class as Model. We now find ourselves quite embarassed: we have to admit it, we lied! We defined our Model last time, thanks to the designer. If you don’t believe us, open in the editor TodoEntities.Designer.cs, found under TodoEntities.edmx.
Open the Entities Context et voilà, you will find there your Model class already defined for you. In this project it is not required, but you may extend this class using C#’s partial classes.

Model layer already done and done? Of couse not! This was just the easy part. We still have to create a very simple ViewModel and a Database Abstraction Layer.

The ViewModel

Yes, we learnt our lesson: model, view and controller interact among them as described in the MVC pattern, but we find healtier to use ViewModels for the binding between View and Model. In this project, it is probably quite silly due to the triviality of the Todo model, but we believe it a best-practice to enforce nonetheless.

(Right click on “Todo” Project in the Solution Explorer) Add –> New Folder. Name it “ViewModels”. Then (Right click on “ViewModels” folder) Add –> New Item –> Visual C# –> Web –> Class. Name it “TodoViewModel” and click Add.

New Todo ViewModel

As we said the code for the ViewModel is pretty trivial. We advise to only pay attention to the word capitalization: we use lowercase words here to accomodate the Todo demo’s capitalization.

using System;

namespace Todo.ViewModels
{
    public class TodoViewModel
    {
        public int id { get; set; }
        public string text { get; set; }
        public bool done { get; set; }
        public int order { get; set; }

        public TodoViewModel() { }

        public TodoViewModel(Todo t)
        {
            this.id = t.Id;
            this.text = t.Text;
            this.done = t.Done;
            this.order = t.Order;
        }
    }
}

Easy enough?

Database Abstraction Layer

Once again speaking of best practises, we will avoid directly calling the ORM’s ObjectContext from the Controller. Instead to abstract the database access, we will add a thin layer, unusually named Database Abstraction Layer (DAL). The layer will be loosely based on Fowler’s Repository Pattern. This choice promotes code reuse, testability, centralized access to your database and… well! It tastes nice too!

Let’s create first a DAL folder in the project, (Right click on “Todo” Project in the Solution Explorer) Add –> New Folder. Name it “DAL”. At this point we first write a IRepository interface and then implement it in a TodoRepository.

The Interface

(Right click on “DAL” folder) Add –> New Item –> Visual C# –> Code –> Interface. Name it “IRepository” and click Add.

New IRepository Interface

Below you can find the clean interface code

using System;
using System.Linq;
using System.Collections.Generic;

namespace Todo.DAL
{
    public interface IRepository<T>
    {
        IQueryable<T> FindAll();
        T Get(int id);
        void Save();
        T Add(T t);
        void Delete(T t);
    }
}

The Repository

Next we will implement the IRepository interface in a TodoRepository.
(Right click on “DAL” folder) Add –> New Item –> Visual C# –> Web –> Class. Name it “TodoRepository” and click Add.

New TodoRepository

Here’s the code

using System;
using System.Collections.Generic;
using System.Linq;

namespace Todo.DAL
{
    public class TodoRepository : IRepository<Todo>
    {
        private TodoEntitiesContainer db = new TodoEntitiesContainer();

        public IQueryable<Todo> FindAll()
        {
            return db.TodoSet;
        }

        public Todo Get(int id)
        {
            return db.TodoSet.FirstOrDefault(c => c.Id == id);
        }

        public void Save()
        {
            db.SaveChanges();
        }

        public Todo Add(Todo todo)
        {
            db.TodoSet.AddObject(todo);
            return todo;
        }

        public void Delete(Todo todo)
        {
            db.TodoSet.DeleteObject(todo);
        }
    }
}

If some of you are disappointed by the results, let’s summarize what have we accomplished:

  • discovered the Todo model class, already created by the Entity Framework Designer;
  • provided a separation between the Model and the View thanks to the use of a TodoViewModel;
  • abstracted the database and restricted its access to only a subset of methods through the IRepository interface;
  • implemented the interface with a specialized TodoRepository class;
  • built a self-contained Model layer, which could be moved in a different VS project, should the need arise

Not so bad, uh? See you for the next part: the Controller!

Tags: , , , , , , ,

{ 6 comments to read ... please submit one more! }

  1. Please submit third!! can you post the application to download

  2. The persistence layer is easy. Where’s your Part 3 where we actually see how Backbone plugs into a RESTful MVC server-side setup?

  3. Working on it…stay tuned! ;)

{ 3 Pingbacks/Trackbacks }

  1. ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part III » Bit Candies
  1. Building a demo chat app in MVC3, backbone.js and a little SignalR for fun… | Rick Schott :: devlpr.net
  1. ASP.NET MVC3 RESTful application tutorial with Backbone.js – Part IV » Bit Candies

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>