Pallet Town: Intro to the Repository Pattern MVC4 pt 2

Pallet TownWelcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

This week we are carrying on with our introduction to the repository pattern in ASP.Net MVC4. We’ve done well so far if I can be allowed to say so myself, but we left one glaring issue in our application: we forgot to persist our data.

Let’s start by adding a database context to our existing Pokemon class:

namespace PokeSample.Models
{
  public class Pokemon
  {
     public int Id { get; set; }
     public String Name { get; set; }
  }

  public class PokemonContext
  {
     public DbSet PocketMonsters { get; set; }
  }

}

Now let’s actually use out PokeContext in our repository:

namespace PokeSample.Models
{
  public class PokeRepository : IPokeRepository
  {
    private PokemonContext db = new PokemonContext()
    private List pokemon = new List();
    private int nextId = 0;

    public PokeRepository()
    {
       this.pokemon = db.PocketMonsters.ToList();
    }

    public Pokemon Add(Pokemon somePokemon)
    {
        if (somePokemon == null)
        {
           throw new ArgumentNullException("somePokemon is null");
        }

        somePokemon.Id = nextId++;
        pokemon.Add(somePokemon);
        db.PocketMonsters.Add(somePokemon);
        db.SaveChanges();

        return somePokemon;
    }

    public Pokemon Get(int id)
    {
       return pokemon.Find(p => p.Id == id);
    } 
  }
}

That’s it! If you are running on localhost with Visual Studio 2012, the data will be saved to a .mdf file on your App_Data directory. If you are running on Azure and publishing with a publisher profile, then it should all be set up for you, assuming you have properly set up a Azure site with a corresponding SQL database on the Azure web portal.