Friday 13 February 2015

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.




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