I have been working on the next version of my blog recently, and one of the updates is upgrading Entity Framework to version 5.0. When I initially set up the blog, I used EF4 that came with VS2010. The upgrade process from version 4.0 has to be done manually; using NuGet for the upgrade can only automatically update to versions 4.1 and above.

Yesterday, I worked on it for a long time, and finally got the website up and running. Here's what I learned from the experience.

Step 1: Install Entity Framework 5.0 from NuGet


First, do not make any changes or deletions to the existing EF4.0 project. Directly install EF5 from NuGet. If your project is based on .NET 4, what you're actually installing is the 4.4 version of the DLL, so the enumeration types of EF5 cannot be used. If you have already upgraded to .NET 4.5, then it is fully EF5.

NuGet will automatically add references and configure the relevant config files for you.

Step 2: Update EDMX


Open an existing EDMX file, right-click on the blank space, and select "Add Code Generation Item"

The new version of EF uses the T4 template to generate entity classes, while in 4.0 it is in an edmx, so we have to choose a template, and there is obviously only one option here:

EF 5.x DbContext Generator

VS will then pop up several dialog boxes asking if you dare to run the build script. Obviously we want to confirm the run. After a while, your new version of the EF entity class is generated:

Step 3: Update the CUD method


Now, your program won't compile. Since EF4.0, the APIs that have been added, deleted, and modified have changed. So we're going to make some changes to the old code.

1. Insert: This is now done using context.Type.Add(object).

2. Delete: This is now done using context.Type.Remove(object).

3. Update operation: Attach is not needed now, use context.Entry.State = System.Data.EntityState.Modified

4. If you also need an ObjectSet<T> type, you must use an adapter to force it:

(context as IObjectContextAdapter).ObjectContext.CreateObjectSet<Type>();

Compile the program again, and it should be ready to use~