Friday, 13 February 2015

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

       


No comments:

Post a Comment

Paging in html table using javascript

I demonstrated how to use HTML tables on the client for a very simple client-side paging solution. I have heard from several people who p...