Seed Databases in EntityFramework

When we begin working on an application, we spend most of the time creating a database and tables, but in Entity Framework, there is the advantage that it can automatically create, update, and drop databases when the application runs.

EF suggests using "Database Migrations" to prevent losing databases or records. Usually, we do not use "Database Migrations" in our normal application and for this EF we have the database "Seed" method that allows you to seed some dummy data in the database for testing purposes and this could be used in our applications such as MVC, ASP.NET, Windows Forms apps and so on.

To seed data into a database, you need to create a custom DB initializer as in the following.

  • DropCreateDatabaseIfModelChanges<DBContext>
  • CreateDatabaseIfNotExists<DBContext>
  • DropCreateDatabaseAlways<DBContext>

Now we will create an application with a seed method.

Step 1. Create a new project. Open Visual Studio and click New Project, then select Visual C# and create WindowsFormsApplication1.

Step 2. Install Entity Framework. The process of installing Entity Framework is shown in my previous tutorial “Nuget Package Manager”.

Nuget Package

Step 3. Add a class for Students to define the parameters.

Right-click on the Solution Explorer add a class and define an attribute in this class using the Code First approach.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

 Parameters

Step 4. Add another class for StudentEntity to define the DbContext.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace WindowsFormsApplication1
{
    class studentEntity : DbContext
    {
        public DbSet<Student> Students { get; set; }
    }
}

Here we must remember that we need to a "using System.Data.Entity;" as in the following/

.Data.Entity

Step 5. Database Initializer.

Add a new class for Database initialize and now put the data for showing when the database was first created.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace WindowsFormsApplication1
{
    class StudentDataBaseInitializer : DropCreateDatabaseIfModelChanges<studentEntity>
    {
        protected override void Seed(studentEntity context)
        {
            var students = new List<Student>
            {
                new Student
                {
                    FirstName = "Munesh", LastName = "Sharma"
                },
                new Student
                {
                    FirstName = "Vinod", LastName = "Roy"
                },
                new Student
                {
                    FirstName = "Manish ", LastName = "Kumar"
                },
                new Student
                {
                    FirstName = "Rohit ", LastName = "jash"
                },
                new Student
                {
                    FirstName = "gautam", LastName = "shree"
                }
            };
            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();
        }
    }
}

code

Step 6. Seed data into the database. We use the following line for seeding the data into the database.

Database.SetInitializer<studentEntity>(new StudentDataBaseInitializer());

Step 7. Display in the form. Add a form and use a button and then write the following code on the button click.

Display

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Entity;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using(var context = new studentEntity())
            {
                Database.SetInitializer < studentEntity > (new StudentDataBaseInitializer());
                //This is linq query
                var stdInfo = (from C in context.Students
                               select new
                               {
                                   Id = C.StudentId, FirstName = C.FirstName
                               });
                foreach(var info in stdInfo)
                {
                    Console.WriteLine("ID : " + info.Id + ", Name : " + info.FirstName);
                }
                Console.ReadKey();
            }
        }
    }
}

Result

After clicking on the button you will see the result with FirstName and LastName.

You can view the same article on my blog.