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.


Fill Gridview from DataBase in Entity framework

In this tutorial we will learn that how to fill data in gridview from database using entity framework.
First of all before doing this we have to install entity framework  as I mention in tutorial 1.
Lets understand Entity framework with an example , Here we have two tables “Student” and “Subject “ .
“Subject”  Table is
SubjectID
SubjectName
Branch
1
C++
IT
2
Microprocessor
EC
3
Thermo Dynamics
Mechanical

“Student”  table
Student ID
First Name
Last Name
Gender
Subject ID
1
Munesh
Sharma
MALE
1
2
Anshuman
Sharma
MALE
2
3
Megha
Sharma
Female
1
4
Hema
Garg
Female
3
5
Rahul
Sharma
Male
2

We want output like below
SubjectID
SubjectName
Branch
SudentDetail
1
C++
IT
FirstName
LastName
Gender
Munesh
Sharma
Male
Megha
Sharma
Female
2
Microprocessor
EC
FirstName
LastName
Gender
Anshuman
Sharma
Male
Rahul
Sharma
Male
3
Thermo Dynamics
Mechanical
FirstName
LastName
Gender
Hema
Garg
Female

Step(1) : To need this We have install entity framework as i told you before.
Step(2): after that you create two classes for Subject and Student.
public class Subject
    {
        public Subject()
        { 
        
        }
    Subject ID { get; set; }
    SubjectName { get; set; }
}
     Branch { get; set; }
public ICollection<Student> Students { get; set; }

)

Student Class is :>
public class Student
    {
        public Student()
        {
       
        }
        public int StudentID { get; set; }
        public string StudentFirstName { get; set; }
        public string StudentLastName { get; set; }
       public string Gender { get; set; }       

        public Subject Subject { get; set; }
 }
}
   
Step(3): After that  You design your gridview There you put your gridview inside gridview and give the connection and write the ADO.Net code for retrieve the code.
Design Your gridview Like this

SubjectID
SubjectName
Branch
SudentDetail



FirstName
LastName
Gender















Step(4):  Create "Subject" and "Student" tables.
Create table Subject
(
    SubjectID int primary key identity,
     Name nvarchar(50),
     Branch nvarchar(50)
)

Create table Student
(
    StudentID int primary key identity,
     FirstName nvarchar(50),
     LastName nvarchar(50),
     Gender nvarchar(50),
     SubjecttId int foreign
)
Step(5):  Insert values in tables
Insert into Subject values ('C++''IT')
Insert into Subject values ('Microprocessor', ‘EC’)
Insert into Subject values ('Thermo Dyanamic''Mechenical')

Insert into Student values (‘Munesh’'Sharma''Male', 1)
Insert into Student values ('Hema''Garg''Female',  3)
Insert into Student values ('Megha''Sharma''Female',  1)
Insert into Student values ('Anshuman''Sharma''Male',  2)
Insert into Student values ('Rahul''Sharma''male',  2)

Step(6):  Now Right click on solution explorer and add new item as ADO.Net Entity Data Modal And change the name as Student.edmx




Step(7):  when you will click on add button Wizard window will open from there you click on “ Generate from database”  and go next there you select your connection .



Step(8):  After giving proper connection you ensure that the checkbox “Save Entity connection setting in web.config”  should be checked.
 After giving name of this click on next here you will see two table, one for student and another for subject table.
Here at this screen you select the both tables and click OK , After click OK you will see both table parameters as in entity Data modal.



Step 9: Add a webform. Drag and drop a GridView from toolBox and an EntityDataSource control.

Step 10: Build the solution. WebForm Design Screen.
a) Go to “Show Smart tag” by right click on EntityDataSource.
b) And "Configure Data Source"
c) Select "Named Connection" radio button and select "EmployeeDBContext" from the dropdown list.
d) Select "EmployeeDBContext" option from "DefaultContainerName" dropdownlist and click Next.
e) On this screen select table name as Student
f) Go to “show Smart tag” of gridview and select data source  as EntityDataSource .
G) Click on "Eidt Columns" and add a "Template Field". Set HeaderText=Sudents  and click OK.
H) Click "Edit Templates" link and drag and down a Gridview from tool box.
l) Click  "Edit DataBindings" link
J) Select "Custom binding" radio button and type Eval("Students") in "Code expression" textbox and click OK.
K) Select "End Template Editing" option from "GridView1" smart tasks.














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...