Friday, 13 February 2015

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.














Database Initialization Strategies in Code-First Entity framework

As we  know when we run our application then its automatically create database. But about 2nd time , it will create database or it will change in database tables or 2nd time it create new database. To handle all these type of task you have to use one of them database initialization strategies.
There are four type of database initialization strategies.
  1. CreateDatabaseIfNotExists:  This is default initializer. As name Shows, it will create the database if none exists as per  configuration. After that  if you make  changes  in the application  class and run the application with this initializer, then it will  give an exception.
  2. DropCreateDatabaseIfModelChanges:  This  initialize  leave existing database and create a new database, if your entity classes (application classes) have been changed. So after that it will maintain your database.
  3. DropCreateDatabaseAlways:   IF we go to this initialize its shows that it drop database always when you run your application whatever you have made any changes or not in class. Actually this initialize is useful when we need new database when you want to run your application.
  4. Custom DB Initializer:   Suppose if any of the above do not satisfy your requirement then you also can make your custom  initialize other thing if you want to use above 3 initializer then  you have to do another process.
 To use one of them  initializer, you have to set  DB Initializer using Database class in Context class as shown below :
    
    public class CompanyDBContext: DbContext
    {
       
        public CompanyDBContext(): base("CompanyDBConnectionString")
        {
            Database.SetInitializer<CompanyDBContext>(new CreateDatabaseIfNotExists<CompanyDBContext>());

            //Database.SetInitializer<CompanyDBContext>(new DropCreateDatabaseIfModelChanges<CompanyDBContext>());
            //Database.SetInitializer<CompanyDBContext>(new DropCreateDatabaseAlways<CompanyDBContext>());
            //Database.SetInitializer<CompanyDBContext>(new CompanyDBInitializer());
        }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Department> Department { get; set; }
    }

If you want to create your custom class then
   
    public class ComapanyDBInitializer :  CreateDatabaseIfNotExists<CompanyDBContext>
    {
        protected override void Seed(CompanyDBContext context)
        {
            base.Seed(context);
        }
    }
     

       


Manage DataBase table in Code First approach

In Code First Approach When we declare properties in classes and run the application then its automatically create DataBase Tables As we done it in previous tutorial.
Now the problem is that if we change in parameters  and try to run this application then it gives error. So How to handle this problem. In this tutorial we will solve this type of problem.
In earlier tutorial we create a class of employee with some parameters those are define like that
namespace WindowsFormsApplication1
{
   public class Employee
    {
       public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }             
    }}
Now i want to add a new properties in this  Employee class as “ EmployeePlace”  then this class will show like that
namespace WindowsFormsApplication1
{
   public class Employee
    {
       public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }             
        public string EmployeePlace { get; set; }
    }}
Now if we run this application then this application will give error that database and the properties define in class is not match or not synchronize.
The model backing the 'EmployeeDBContext' context (Parameter changed )has changed since the database was created.
This is because the Employee class has changed since the database was created. It means Database and the modal(Employee.cs class) is not synchronize, To check that is class change or not EF uses __MigrationHistory table that is auto-generated.
_MigrationHistory  is a table created  by Code First Migrations to store information  about migrations applied to the database.

To remove this error, we have to inform to EF that some changes has done. For this we have to add a Global.Asax.
When you open this class then there are some method already predefine methods there we have to give definition. There you add  System.Data.Entity namespace.
Public  Application_Start(object sender , Event Args e) 
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EmployeeDBContext>());
}
You can write it in different way
Public  Application_Start(object sender , Event Args e) 
{
Database.SetInitializer(new DropCreateDatabaseAlways<EmployeeDBContext>());
}



Now you run your application this will run successfully.




Code first approach In Entity frameWork

Code-first approach we have to create custom classes and based on those custom classes entity framework can generate database automatically for us.
POCO :- POCO class is the class which doesn’t depend on any framework specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects” These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as Entity Object derived entities.
In code First approach we doesn’t work on designer.tt(EDMX). You have to write POCOs classes for this as before I explained you about POCO classes. For creating Code First approach in entity framework First you have to install Entity framework as I shown you in earlier tutorial. Go to your nugget package manager and  search on online as entity framework and download.
Example for Code first approach.
We will understand code first approach with an example of an employee where a user able to add employee and update information of an employee. For this first we have to create classes of the properties of employee. After that we will design database.
Add a class there you put these Below  properties those are defined for an employee.
namespace WindowsFormsApplication1
{
  
   public class Employee
    {
       public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime? DateOfBirth { get; set; }    
       
    }

}

Now we have defined properties of employees. Code first approach needed a Context  class .This class is derived from DBContext. DbContext  is a Collection of entities. So when we have to inebriate this class in defined class.
Add a class name is “CodeFirsrApproach.cs”
using System.Data.Entity;

namespace WindowsFormsApplication1
{
    class CodeFirsrApproach : DbContext
    {
// we will tell the context what should be created in the database Add the following line:
        public DbSet<Employee> Employees { get; set; }          

    }
}            
 
DbSet is a collection of entities.
This ensure us to that it will contain the collection of all employee information and table employee will created. Now you check your SQLServer instance and add this below code in programe.cs class
    var person = new Employee
            {
                FirstName = "Munesh",
                LastName = "Sharma",
                DateOfBirth = DateTime.Now
            };
            using (var context = new CodeFirsrApproach())
            {
                context.Employees.Add(person);

                context.SaveChanges();
            }
            Console.Write("Employee information saved");
            Console.ReadLine();
SaveChanges() is a method which automatically save the data. So when you will run this application its automatically save a data in database.
Now you go to your Sql server database there you see will your tables with and fields. There we no need to pass any parameter it automatically create table in local machine.  



 

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