Improving Entity Framework by using code first

In this recipe, we start by separating the application into a user interface, a data access layer, and a business logic layer. This will allow us to keep our objects segregated from database-specific implementations. The objects and the implementation of the database context will be a layered approach so we can slot testing and abstraction into the application.

Getting ready

We will be using the NuGet Package Manager to install Entity Framework 4.1 assemblies.

The package installer can be found at http://www.nuget.org/. We will also be using a database in order to connect to the data and update it.

Open Using Code First Solution from the included source code examples.

Execute the database setup script from the code samples included for this recipe. This can be found in the DataAccess project within the Database folder.

How to do it...

Let us get connected to the database using the following steps:

  1. In the BusinessLogic project, add a new C# class named Blog with the following code:
    using System;
    namespace BusinessLogic
    {
      public class Blog
      {
        public int Id { get; set; }
        public string Title { get; set; }
      }
    }
  2. In the DataAccess project, create a new C# class named BlogContext with the following code:
    using System.Data.Entity;
    using BusinessLogic;
    namespace DataAccess
    {
      public class BlogContext : DbContext
      {
        public BlogContext(string connectionString) : base(connectionString)
        {
        }
        public DbSet<Blog> Blogs { get; set; }
      }
    }
  3. In the Recipe1UI project, add a setting Blog with the connection string shown in the following screenshot:
    How to do it...
  4. In the UI project in the BlogController.cs, modify the Display method with the following code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using BusinessLogic;
    using DataAccess;
    using UI.Properties;
    namespace UI.Controllers
    {
      public class BlogController : Controller
      {
        private BlogContext _blogContext;
        public BlogController() :this(new BlogContext(Settings.Default.BlogConnection)) { }
        public BlogController(BlogContext blogContext)
        {
          _blogContext = blogContext;
        }
        // GET: /Blog/
        public ActionResult Display()
        {
          Blog blog = _blogContext.Blogs.First();
          return View(blog);
        }
      }
    }

How it works...

The blog entity is created but not mapped explicitly to a database structure. This takes advantage of convention over configuration, found in the code first approach, wherein the properties are examined and then table mappings are determined. This is obviously a time saver, but it is fairly limited if you have a non-standard database schema. The other big advantage of this approach is that the entity is "persistence-ignorant". In other words, it has no code or knowledge of how it is to be stored in the database.

The blog context in the DataAccess project has a few key elements to understand. The first is to understand that the inheritance from DbContext. DbContext is the code first version of ObjectContext, which runs exposing all connection pooling, entity change tracking, and database interactions. We added a constructor to take in the connection string, but note that this is not the standard connection string used with the database-first and model-first approaches to the embedded Entity Framework metadata connection string. Instead, the connection string is a standard provider connection string. You can also pass the name of an application setting through here, but the recommended approach is to provide the full connection string after it has been retrieved from the application settings store.

We used the standard built-in functionality for the connection string, but this could easily be any application setting store. Larger applications require more flexibility for where the settings are stored so we pass in the connection string on the construction of the BlogContext. It enables us to source that connection string from anywhere.

We did need to pass in the BlogContext as a parameter of the controller. Doing so allows us to interact with the database. The context here allows us to access the collection of objects that directly translate to database objects at request time.

There's more...

Approaching the use of code first development, we have several overarching themes and industry standards that we need to be aware of. Knowing about them will help us leverage the power of this tool without falling into the pit of using it without understanding.

Convention over configuration

This is a design paradigm that specifies default rules about how each aspect of an application will behave, but allows the developer to override any of the default rules with specific behavior required by the application. This allows us, as programmers, to avoid using a lot of configuration files to specify how we intended something to be used or configured. In our case, Entity Framework allows the most common behaviors to use default conventions that remove the need for a majority of the configurations. When the behavior we wish to create is not supported by the convention, we can easily override the convention and add the required behavior to it without the need to get rid of it everywhere else. This leaves us with a flexible and extendable system to configure the database interaction.

Model-View-Controller

In our example, we use Microsoft ASP.NET . We are using MVC (Model-View-Controller) framework to deliver the User Interface (UI) because it builds a naturally testable model to house our code. You will see that we predominantly used the MVC approach in our examples. The implementations can be ported to any UI, or no UI for that matter at all, if that is your preference. All of our samples use the MVC 3 Framework and Razor view engine for rendering the UI. We have provided some simple views which will allow us to focus on the solutions and the code without needing to deal with UI design and markup.

Single responsibility principle

One of the solid principles of development, that is, the single responsibility principle, states that every class should have only one reason to change. In this chapter, there are several examples of that in use. For example, the separation of model, view and controller in MVC. However, this important tenant is also why we favor the code first approach to begin with.

Entities in code first have the structure of data as their singular responsibility in memory. This means that only if the structure needs to be changed will we need to modify the entities. By contrast, the code automatically generated by the database-first tools of Entity Framework inherits your entities from base classes within the Entity Framework Application Programming Interface (API). The process of Microsoft making occasional updates to the base classes of Entity Framework is the one that introduces a second reason to change, thus violating our principle.

Testing

While we did not actively test this recipe, we did layer in the abstractions to do so. All of the other recipes will be executed and presented using test-driven development, as we believe it leads to a better software design, and a much more clear representation of intent.

See also

In this chapter:

  • Implementing the unit of work pattern
  • Implementing the repository pattern
..................Content has been hidden....................

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