Entity Framework's Database Seed Method

The Entity Framework can automatically create/update/drop databases when the application runs. We can specify that this should be done every time the application runs or only when the model is out of sync with the existing database or in other words it runs whenever the model changes. You spent the time to insert records in the database and when you made any changes in the model, the Entity Framework deletes your database as well as records.
 
The Entity Framework recommends the use of "Database Migrations" to stop loss of a Database or of Records. Usually, we don't use "Database Migrations" in our normal application development and for this, the Entity Framework has the Database "Seed" Method that allows you to seed some dummy data in the database for testing purposes and this could be used in MVC, ASP.NET Web Forms, Windows Form apps, etc.  
 
Creating a database initializer can be done by inheriting from either of the generic classes:
  • DropCreateDatabaseIfModelChanges<DBContext>
  • DropCreateDatabaseAlways<DBContext>
Now, follow the steps to set up a demo Console Application, and then we will explore the "Seed Method".
 
Step 1: Create a New Project
 
Create a new console application "File" > "New" > "Project..." then "Visual C#" > "Console Application".
 
Step 2: Install EF5 from NuGet
 
At the very first, we need to enable the Entity Framework 5 for this console project from the NuGet Package Manager. For this, in "Solution Explorer" right-click on the project and click on "Manage NuGet Packages" and install Entity Framework 5. Alternatively, you can install this using the power console using the command "Install-Package EntityFramework".
 
Step 3: Create a Model
 
Now to define a new model using the Code First Approach.  
  1. public class Student  
  2. {  
  3.     public int StudentId { getset; }  
  4.     public string Name { getset; }  
  5.     public string Address { getset; }  
Step 4: Create DbContext
 
Now, go ahead and define the DbContext.  
  1. public class StudentContext : DbContext  
  2. {  
  3.     public DbSet<Student> Students { getset; }  
Note: To use the namespace put "using System.Data.Entity;" at the top.
 
Step 5: Database Initializer (Dummy Data)
 
Now we are done with the Model and DbContext. Let's decide what data we want to initialize when the database is first created. This can be done using any class that inherits DropCreateDatabaseIfModelChanges<StudentContext> or DropCreateDatabaseAlways<StudentContext>. The first one will be called when the model is changed and the second one will be called each time we run the application. I'm using the first one. We can place this code in a separate class file also.
  1. public class StudentDbInitializer : DropCreateDatabaseIfModelChanges<StudentContext>  
  2. {  
  3.     protected override void Seed(StudentContext context)  
  4.     {  
  5.         var students = new List<Student>  
  6.         {  
  7.             new Student { Name = "Abhimanyu K Vatsa", Address = "Bokaro" },  
  8.             new Student { Name = "Deepak Kumar Gupta", Address = "Bokaro" },  
  9.             new Student { Name = "Manish Kumar", Address = "Muzaffarpur" },  
  10.             new Student { Name = "Rohit Ranjan", Address = "Patna" },  
  11.             new Student { Name = "Shivam", Address = "Motihari" }  
  12.         };  
  13.         students.ForEach(s => context.Students.Add(s));  
  14.         context.SaveChanges();  
  15.     }  
Step 6: Seed Dummy Data to Database
 
So, we have dummy data that I will seed to the database and the database will be created at run time. Now, we need to make a call, here you go.  
  1. Database.SetInitializer<StudentContext>(new StudentDbInitializer()); 
Step 6: Complete Code  
 
Find the complete code of my console application.  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace ConsoleApplication5_Seed {  
  9.     public class Student {  
  10.         public int StudentId { get;  
  11.             set; }  
  12.         public string Name { get;  
  13.             set; }  
  14.         public string Address { get;  
  15.             set; }  
  16.     }  
  17.   
  18.     public class StudentContext: DbContext {  
  19.         public DbSet < Student > Students { get;  
  20.             set; }  
  21.     }  
  22.   
  23.     public class StudentDbInitializer: DropCreateDatabaseIfModelChanges < StudentContext > {  
  24.         protected override void Seed(StudentContext context) {  
  25.             var students = new List < Student > {  
  26.                 new Student { Name = "Abhimanyu K Vatsa", Address = "Bokaro" },  
  27.                 new Student { Name = "Deepak Kumar Gupta", Address = "Bokaro" },  
  28.                 new Student { Name = "Manish Kumar", Address = "Muzaffarpur" },  
  29.                 new Student { Name = "Rohit Ranjan", Address = "Patna" },  
  30.                 new Student { Name = "Shivam", Address = "Motihari" }  
  31.             };  
  32.             students.ForEach(s => context.Students.Add(s));  
  33.             context.SaveChanges();  
  34.         }  
  35.     }  
  36.   
  37.     class Program {  
  38.         static void Main(string[] args) {  
  39.             using(var context = new StudentContext()) {  
  40.                 Database.SetInitializer < StudentContext > (new StudentDbInitializer());  
  41.   
  42.                 var stdQuery = (from d in context.Students select new { Id = d.StudentId, Name = d.Name });  
  43.   
  44.                 foreach(var q in stdQuery) {  
  45.                     Console.WriteLine("ID : " + q.Id + ", Name : " + q.Name);  
  46.                 }  
  47.   
  48.                 Console.ReadKey();  
  49.             }  
  50.         }  
  51.     }  
Now, if you run the application you will see all the dummy data that we have created and initialized above.
 
 
Step 7: MVC Apps  
 
I am an ASP.NET guy, so I'd like to tell something here on MVC. In MVC we call the SetInitializer method from Application_Start() method that can be found in Global.asax.cs file. Find here a sample:
  1. protected void Application_Start()  
  2. {  
  3.     System.Data.Entity.Database.SetInitializer(new StudentDbInitializer());  
  4.   
  5.     AreaRegistration.RegisterAllAreas();  
  6.   
  7.     WebApiConfig.Register(GlobalConfiguration.Configuration);  
  8.     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  9.     RouteConfig.RegisterRoutes(RouteTable.Routes);  
I hope you like it. Thanks.