.NET Entity Framework: Using Database Migration to Seed a Database

If you have been following along, you know that I’ve been writing a series of posts on the .NET Entity Framework, and this post is the last in the series.

The Entity Framework (EF) is an object-relational database mapper that enables easy database access for .NET developers using domain-specific .NET objects that EF can generate for you. As shown in the Using Database Migration post, you can easily use EF to create your database from the classes that are defined in your project code. You can then use Code First Migrations to handle any database changes for the life cycle of your application.
During the course of developing your application (or during the testing phase), you often make changes either to the data collected or to the way data is processed. Sometimes you may have a bug in your code that has let corrupt or incorrect data get into your database. This can give you unpredictable results, and you can end up dropping and creating a database multiple times. When this happens, you are sometimes faced with the undesirable task of getting data back into the database to test your bug fixes. In the past this was a painstakingly slow process, since you had to add all of your test data back into the database.

Well, Entity Framework and Code First Migration has a solution for that. In the last blog post on Data Migration, you saw that running the Enable-Migrations -ContextTypeName SafariCodeFirst.SeminarContext command created a Migrations folder and two C# source files:

As previously described, the Configuration.cs file contains the settings for Migrations to work its magic, which in this case is to seed the database. If you examine Configuration.cs, you will see that Migrations has already created a stub method called Seed as the code below shows. It even contains some commented out code that shows how to go about adding a seed data to the table.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

namespaceSafariCodeFirst.Migrations

{

using System;

using System.Data.Entity;

using System.Data.Entity.Migrations;

using System.Linq;

internal sealed classConfiguration:DbMigrationsConfiguration

{

publicConfiguration()

{

AutomaticMigrationsEnabled=false;

}

protectedoverride voidSeed(SafariCodeFirst.SeminarContext context)

{

// This method will be called after migrating to the latest version.

// You can use the DbSet&lt;T&gt;.AddOrUpdate() helper extension method

// to avoid creating duplicate seed data. E.g.

//

// context.People.AddOrUpdate(

// p =&gt; p.FullName,

// new Person { FullName = "Andrew Peters" },

// new Person { FullName = "Brice Lambson" },

// new Person { FullName = "Rowan Miller" }

// );

//

}

}

}

Let’s remove the commented out code (or leave it for future reference) and add the code to seed the database as shown here:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

protectedoverride voidSeed(SafariCodeFirst.SeminarContext context)

{

context.Seminars.AddOrUpdate(

p=&gt;p.Name,

newSeminar

{

Name="Seed Seminar One",

Speaker="Marshall Harrison"

},

newSeminar

{

Name="Seed Seminar Two",

Speaker="Marshall Harrison"

},

newSeminar

{

Name="Seed Seminar Three",

Speaker="Marshall Harrison"

}

);

}

You can see how the Context.Seminars.AddOrUpdate helper class is used to create three new seminars if they don’t exist. If the database rows exist, then they will be updated. One thing to note is that you need the line that reads p => p.Name, or you will add all three seminars each time you run Update-Database, since that is used to identify the records.

So now that the code is ready, let’s delete all of the rows in the table and then run Update-Database. Your database should look like the following figure after the command finishes running:

Let’s make one small change to the code and prove that the Seed method will update the existing rows if they already exist. Change the Speaker for “Seed Seminar Three” to read “Jim Smith” and run the Update-Database command again, and then check the results. You will see that this time, instead of adding records, the data was simply updated.

As shown here, you can use Entity Framework and Code First Migrations to seed your database and make your life as a developer a lot easier. Of course, there are other things that configuration.cs can be used for, but I hope I have piqued your interest in Entity Framework so you will start experimenting with it on your own.

Safari Books Online has the content you need

Check out these .NET Entity Framework books available from Safari Books Online:

Programming Entity Framework: Code First acts as an extension to Programming Entity Framework 2nd Edition. Code First is an additional means of building a model to be used with the Entity Framework and is creating a lot of excitement in the .NET development community. The book begins with an overview of what Code First is, why it was created, how it fits into the Entity Framework and when to use it over the alternatives.

Entity Framework 4 in Action is an introduction to the Entity Framework for developers working in .NET who possess a working knowledge of ADO.NET. Beginning with a review of the core ideas behind the Object Relational Management (ORM) model, it outlines how the Entity Framework offers a smooth transition from a traditional ADO.NET approach. Featuring numerous examples and in-depth case studies, the book explores the Entity Framework story in clear, easy-to-follow detail.

Entity Framework 4.1: Expert’s Cookbook holds many examples to help guide you through tough technical decisions and avoid technical landmines. The book will guide you from just using Entity Framework to enhancing the data access wizard. You will be guided through complex mapping scenarios, query definition, reusability, integration with other technologies, and architectural management. The approach is step-by-step and test driven so that it is focused as much as possible on solving problems and getting the most out of the time spent working through the book.

About the author

Marshall Harrison is the founder of GotSpeech.Net and GotUC.net as well as the owner and CEO of GotSpeech Consulting LLC. He holds a B.S. degree in Computer Science and was a Microsoft MVP from 2006 – 2011. He is currently focusing on Microsoft Lync as well as Windows 8 and Windows Phone 8 devleopment. He can be reached through his blog at GotspeechGuy.com.