Welcome 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.
I’ve been having a great time with Windows Azure or more specifically ASP.Net MVC4. .Net developers will be familiar with the repository pattern, since it is a common pattern used in that community. Let’s take a look at a simple repository example using everyone’s favorite objects: Pokemon. To start we need a simple Pokemon class.
namespace PokeSample.Models
{
public class Pokemon
{
public int Id { get; set; }
public String Name { get; set; }
}
}
We now need to create an interface:
namespace PokeSample.Models
{
interface IPokeRepository
{
Pokemon Add(Pokemon pokemon);
Pokemon Get(int id);
}
}
And now it’s time for the repository itself:
namespace PokeSample.Models
{
public class PokeRepository : IPokeRepository
{
private List pokemon = new List();
private int nextId = 0;
public PokeRepository()
{
// adding some test data
Add(new Pokemon { Name = "Charmander"});
}
public Pokemon Add(Pokemon somePokemon)
{
if (somePokemon == null)
{
throw new ArgumentNullException("somePokemon is null");
}
somePokemon.Id = nextId++;
pokemon.Add(somePokemon);
return somePokemon;
}
public Pokemon Get(int id)
{
return pokemon.Find(p => p.Id == id);
}
}
}
You’ll notice that we are seeding the ‘pokemon’ List and have creates some simple CRUD methods. The idea here is that you could call these methods in response to HTTP requests from the PokemonController. Assuming you’ve setup your dev environment correctly this should all work just fine on localhost.
However, there is one pretty obvious glaring issue with this implementation — the data is not persisted. Stay tuned for the part 2 of this series that will show how you can use the common DBContext (ok that’s my term but it’s catchy) pattern to persist your data using MSSQL or some other datastore.
Hope you enjoyed this first entry in Pallet Town and I would appreciate any feedback you might have to offer. Please feel free to contact me on Twitter or Google+.