Data Access

The NuGet Gallery uses the “Code First” approach with Entity Framework 4.3.1 running against a SQL Server 2008 database. When you run the code locally, it runs against a SQL Server Express instance.

Code First is heavily convention-based and requires very little configuration by default. Of course, developers tend to be an opinionated lot with strong personal preferences and need to customize everything they touch, and the NuGet team is no different. There are a few conventions we replaced with our own configuration.

The EntitiesContext class contains our custom configuration for Entity Framework Code First. For example, the following snippet configures the property named Key as the primary key for the User type. If the property name had been Id, or if the KeyAttribute were applied to the property, this line would not be necessary.

modelBuilder.Entity<User>().HasKey(u => u.Key);

One exception to this convention is the WorkItem class, because that class comes from another library.

All the Code First entity classes are located in the Entities folder. Each entity implements a custom IEntity interface. The interface has a single property, Key.

The NuGet Gallery doesn't access the database directly from a DbContext derived class. Instead, all data is accessed via an IEntityRepository<T> interface.

public interface IEntityRepository<T> where T : class, IEntity, new()
{
    void CommitChanges();
    void DeleteOnCommit(T entity);
    T Get(int key);
    IQueryable<T> GetAll();
    int InsertOnCommit(T entity);
}

This abstraction made writing unit tests for our services much easier. For example, one of the constructor parameters for the UserService class is IEntityRepository<User>. In our unit tests, we can simply pass in a mock or fake implementation of that interface.

But in the live application, we pass in a concrete EntityRepository<User>. We accomplish that by using dependency injection using Ninject, a dependency injection framework covered later in this chapter. All our Ninject bindings are located in the ContainerBindings class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset