EntityFramework CodeFirst – DbContext Initializer


We already discussed about the EntityFramework CodeFirst approach and how we can generate the database out of the Code in http://www.dotnetfunda.com/articles/article1358-entity-framework-codefirst-model-.aspx

 Now, let us see how we can handle the changes to the class, which is the base class for the database tables. We may need to propagate the changes from class to database tables.

Consider our sample Student class, where we are going to add a new property called Address.

  publicclassStudent    {

        publicint Id { get; set; }

        publicstring FirstName { get; set; }

        publicstring LastName { get; set; }

        public string Address { get; set; }

        publicList<Mark> Marks { get; set; }

    }

 Now run the application and observe the exception indicating that the model got changed.

Model Change Exception

Model Change Exception

Let us see, how we can update the underline Student table with change. For updating the class level changes to table, Open the global.asax file. If you are an ASP.Net developer, you may be aware that the global.asax file contains different application and session level event handlers.

Inside the Application_Start method, define the Database initializer with one among the two options.

DropCreateDatabaseAlways: This will drop and recreate the database in every application start.

DropCreateDatabaseIfModelChanges: This will drop and create the database only if the underlined model changes.

DbInitializer Options

DbInitializer Options

 We will add the DropCreateDatabaseIfModelChanges with our custom DbContext.

        void Application_Start(object sender, EventArgs e)

        {            Database.SetInitializer(newDropCreateDatabaseIfModelChanges<MyDbContext>());

        }

Run the application and observe the new Student table.

Updated Student Table

Updated Student Table

Add data to the table and run the application

Result Screen

Result Screen

We can define our own DbContext Initializer by inheriting  from one among the defined Initializers.

Advertisements

About ambilykk

I am a Technology Evangelist on Microsoft Technologies. I am carrying the passion on Microsoft technologies specifically on web technologies such as ASP .Net and Ajax. My interests also include Azure and Visual Studio. Technology adoption and learning is my key strength and technology sharing is my passion.
This entry was posted in Entity Framework and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s