Friday 13 February 2015

Seed database in EntityFramework

When we start  a work on an application we spent  most of time to create database and tables but  in entity framework  there is advantages that it automatically  create, update and drop databases when the application runs.
EF  suggest to use 'Database Migrations' to prevent from   loosing Database or Records.  Mostly  we do not  use 'Database Migrations' in our normal application and for this EF got Database 'Seed' Method  this  allow you to seed some dummy data in the database for testing purpose and this could be used in our applications like  MVC, ASP.NET, Windows Form apps etc.
To seed data into database, you have to create custom DB initializer,
·                     DropCreateDatabaseIfModelChanges<DBContext>
·                     CreateDatabaseIfNotExists<DBContext>
·                     DropCreateDatabaseAlways<DBContext>

Now we will create a application with seed method.
Step(1) :  create a new project
Open visual studio -> click new project -> Visual C# - > WindowsFormsApplication1.
Step(2) :  First of create this application install Entity framework, process of installing Entity framework i shown you before tutorial throw “ nuget package manager”


Step(4) :  Add a class for Student for defining  parameters.
Right click on the  solution explorer and add a class and define attribute in this class using 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; }
   
    }
}


Step(5) :  Add a another class for StudentEntity  for defining  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 have to remember that we have to use ‘using System.Data.Entity; namespace.

Step(6) :  Database Initializer
Add a new class For Database initialize Now put the data for showing when database 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();
        }

    }
}


Step(7) :  Seed Data to Database
We use this line for Seed the data into database
  Database.SetInitializer<studentEntity>(new StudentDataBaseInitializer());
Step(8)  : show in form
Add a Form and take a button and write the below code on button click


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();
            }
        }
    }
}


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


No comments:

Post a Comment

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...