I’ve recently had the chance to work with Microsoft’s Entity Framework and whilst I mostly like what it does and how it does it, there are a few sticking points that took some working around, so I thought I’d do a post about them, but first, a little introduction.

What is the Entity Framework?

From the MSDN site:

Entity Framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data-access code that developers usually need to write.

The EF can be used in many ways to do many things but my experience has been using the Code-First parts to build and access a database. Code-First is the process where you define one or more model classes that will directly map to a table in the database, tell the EF about them, and it goes off and writes the code needed to create the tables. The real fun is that if you change those models, say you add a new field, you can tell the EF about those changes, and it will create a migration script that will apply those changes to the database. This allows your database design to be incredibly fluid, which really suits the way I like to work.

Setting it up

For this I’m going to assume you’re creating a new website backed by an EF database (there’s some steps for doing a non-web app later). So fire-up visual studio and we’ll start.

Create a new project, I tend to use the ASP.NET MVC 4 Web Application template, since it has most of the stuff I need to get started, I don’t think it matters which variant of this template you pick, since most of that stuff is outside the scope of this tutorial.

Ensure you have the Entity Framework dll referenced in your project, if you don’t (or if it’s out of date, the current version is 6.1.1) you can install (or update) it via the Package Manager Console using the command:

Install-Package EntityFramework

Now let’s make some models. You should have a ‘Models’ folder, I tend to stick them in a sub-folder of this called ‘Database’ (to keep them separate from ViewModels) but that’s just my preference. What you want to do is make a simple class with a few public properties, something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Person
{
    public int Id { get; set; } // If an EF model has a public field called id it will be represented in the table as an auto-incrementing primary id
    public string Name { get; set; }
    public Department Department { get; set; } // You can reference other models too, this will be a foreign key in the table but patched up with the proper values when you query
}

public class Department
{
    public int Id;
    public string Name { get; set; }
    public Person Head { get; set; }
    public ICollection<Person> Staff { get; set; } // Collections work too!
}

Now we need to tell the Entity Framework that these models should be backed by tables. To do that we need a that inherits from a DbContext, it’ll look something like this:

1
2
3
4
5
6
7
8
9
10
public class MyDatabase : DbContext
{
    public Database()
        : base("name=DefaultConnection")
    {
    }

    public DbSet<Person> People { get; set; }
    public DbSet<Department> Departments { get; set; }
}

Each public property of type DbSet will be represented by a table. The string that is being passed in to the DbContext ctor is the name of the connection string to use to connect to the database. This is specified in the Web.config (or in the App.config if you’re in a non-web-based application).

Connection strings are quite a large topic but for working locally you want something that looks like this:

1
2
3
<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=true;AttachDBFilename=|DataDirectory|\MyApp.mdf" />
</connectionStrings>

Your connection string might have an ‘Initial Catalog’ section, you’ll want to get rid of that. The AttachDBFilename is the path to a file which will be the database, it will be created if it does not exist.

So now we have some models and we have some models and we have set up the DbContext, it’s time to actually build the database. Open up the Package Manager Console and type the following:

Enable-Migrations

This will set-up the project to use code-first migrations (so that changes to the models can be reflected in the database)

Add-Migration InitialCreate

This will create a new migration called ‘InitialCreate’. You can later create more migrations with decent names, and even create another migration with the same name, which will over-write the existing one. If you check in your ‘Migrations’ folder now you should have a file with a name that ends in ‘InitialCreate.cs’ if you look at that file you’ll see that it has all the code in it to create the tables.

Update-Database

This will run any migration scripts that have not been run.

Viewing the database

Connecting to your local development database is pretty easy, go to Tools -> Connect To Database and select Microsoft SQL Server (SqlClient) as the Data Source. For the Server name you want ‘(LocalDb)\v11.0’ (which you may recognise from your connection string) then you can use the drop-down to select the database with a name somewhat like the name of the AttachDBFilename from the connection string. The Server Explorer window will open with a list of DataConnections, if you expand the newly created one, and then expand the ‘Tables’ folder you’ll be able to see the tables that the EntityFramework created for you.

And that’s the basics that I know. There’s a lot more to the EntityFramework than this and there’s probably more ways to do things than I’ve outlined here, but this is what’s worked for me the few times I’ve used it.