• Skip to content
  • Skip to primary sidebar
  • Home
  • Angular
  • ASP.NET Core
  • Entity Framework
    • Entity Framework 6
    • Entity Framework Core
  • Crystal Reports
  • C#
  • ASP.NET
  • About Us
    • Privacy Policy
    • Contact Us

TekTutorialsHub

Free Online Tutorials

Custom Database Initializer in Entity Framework

November 26, 2015 by TekTutorialsHub Leave a Comment

Database Initialization
Seed Database in Entity Framework
 

In this tutorial, we will show how to build a Custom Database Initializer in Entity Framework. In our last tutorial Database initializer in Entity Framework, we discussed the built-in initializers. The Entity framework comes with three built-in Initializers. Those are CreateDatabaseIfNotExists, DropCreateDatabaseAlways and DropCreateDatabaseIfModelChanges. You can build your own custom initializer if any of those does not satisfy your needs.

In this article

  • Custom Database Initializer in Entity Framework
    • Using IDatabaseInitializer
    • Using Built In Initializer
    • Registering the initializer in Configuration file
  • The Database class
    • Create
    • CreateIfNotExists
    • Delete
    • ExecuteSqlCommand
    • BeginTransaction
    • Exists
    • Initialize
    • SetInitializer
  • Summary

Custom Database Initializer in Entity Framework

Custom Database initializers are used when if any of the inbuilt initializers does not satisfy your needs. This is useful when you want to have full control over the creation of the database.

You can create the custom Initialiser either by implementing the interface IDatabaseInitializer or by inheriting from one of the built-in initializers.

Using IDatabaseInitializer

You can create Custom Initializer by implementing the IDatabaseInitializer Interface as shown below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
public class EFInitializer : IDatabaseInitializer<EFContext>
    {
        public void InitializeDatabase(EFContext context)
        {
            if (!context.Database.Exists() || !context.Database.CompatibleWithModel(true))
            {
                context.Database.Delete();
                context.Database.Create();
            }
            //context.Database.ExecuteSqlCommand("Custom SQL Command here");
        }
    }
 

In the above Code, we have created Custom initializer EFInitializer. This class implements the IDatabaseInitializer interface.

1
2
3
 
public class EFInitializer : IDatabaseInitializer<EFContext>
 

The IDatabaseInitializer Interface has one method, which we must implement in the derived class. i.e. InitializeDatabase. The InitializeDatabase method is called when the context is created.

1
2
3
 
public void InitializeDatabase(EFContext context)
 

In the InitializeDatabase method, we check whether the database exists or is it compatible with our current model. If not, then it proceeds to delete and create the database.

1
2
3
4
5
6
7
 
if (!context.Database.Exists() || !context.Database.CompatibleWithModel(true))
{
  context.Database.Delete();
  context.Database.Create();
}
 

The behaviour of the above class is same as DropCreateDatabaseIfModelChanges built in initializer

Once you define your custom database initializer class, you can register it in the same way as the predefined initializer class

1
2
3
4
5
6
7
8
9
10
11
12
 
     public class EFContext :DbContext
     {
         public EFContext() : base("EFDatabase")
         {
             Database.SetInitializer(new EFInitializer());
         }
 
         public DbSet<User> Users {get; set; }
 
     }
 

Using Built In Initializer

You can also use the built-in initializers to create the custom database initializer.

1
2
3
4
5
 
public class EFInitialise : DropCreateDatabaseIfModelChanges<EFContext>
{
}
 

The above code creates a custom database initializer EFInitialise by inheriting from the DropCreateDatabaseIfModelChanges initializer. The InitializeDatabase is already implemented by the DropCreateDatabaseIfModelChanges.You can also override the InitializeDatabase provided by the base initializer. This allows you to add any custom logic. The example code is shown below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
      public class EFInitialise : DropCreateDatabaseIfModelChanges<EFContext>
      {
          public override void InitializeDatabase(EFContext context)
          {
              // You can add your code here
 
              //Call the base initialiser
              base.InitializeDatabase(context);
 
              //You can add your code here
          }
      }
 

Registering the initializer in Configuration file

There are two ways you can register your initializer in entity framework. One using the Database.SetInitializer method as shown below

1
2
3
 
Database.SetInitializer(new EFInitializer());
 

The other method is to add it to the configuration file. This is shown below.

1
2
3
4
5
6
7
 
    <contexts>
        <context type="EFGettingStarted.EFContext, EFGettingStarted">
            <databaseInitializer type="EFGettingStarted.EFInitialise, EFGettingStarted" />
        </context>
    </contexts>
 

Remember that the Initializer settings in configuration file take precedence over the initializer set using the SetInitializer method.

The Database class

The initialization of the database is done by the database class. We looked at this class in our previous tutorial. This class provides many methods, which makes it easier to initialize the database. Some of the methods are listed below.

Create

Creates a new database based on the model.

CreateIfNotExists

Creates a new database only if the database does not exist.

Delete

Deletes the database if it exists, otherwise does nothing.

ExecuteSqlCommand

Executes the given SQL query against the database

BeginTransaction

Begins a transaction on the underlying data store connection

Exists

Checks whether or not the database exists on the server.

Initialize

Runs the registered IDatabaseInitializer on this context.

SetInitializer

Sets the database initializer to use for the given context type.

Summary

In this tutorial, we looked at how to create the custom database initializer in entity framework. In the next tutorial, we look at how to seed the database using the custom database initializer to Seed Database in Entity Framework

Database Initialization
Seed Database in Entity Framework
 

Filed Under: Entity Framework

Leave a Reply

wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.
wpdiscuz_captcharefresh
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of

Primary Sidebar

Copyright ©2008-2018

About us Contact Privacy Policy

Feb,22,2019 01:46:18 PM

Copyright © 2019 · Magazine Pro on Genesis Framework · WordPress · Log in

wpDiscuz
Our web site uses cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.OkRead more