Click here to Skip to main content
15,883,705 members
Articles / Entity Framework

EntityFramework CodeFirst – DbContext Initializer

Rate me:
Please Sign up or sign in to vote.
3.67/5 (2 votes)
25 May 2011CPOL1 min read 40K   2   1
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.

C#
public classStudent    {
        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.

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


Filed under: Entity Framework Tagged: DbContext, DropCreateDatabaseIfModelChanges, EntityFramework

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect TCS
India India
I have over 10 years of experience working on Microsoft Technologies. I am carrying the passion on Microsoft technologies specifically on web technologies such as ASP.Net, HTML5, jQuery and Ajax. My interests also include TFS, Azure, Windows 8, Visual Studio 2010. Technology adoption and learning is my key strength and technology sharing is my passion.

Microsoft MVP: Connected Service Developer

Comments and Discussions

 
QuestionDatabase.SetInitializer in WPF application Pin
Clayer5-Dec-11 11:31
Clayer5-Dec-11 11:31 
Hi!
Thanks for your article. I'm using Entity Framework and "Code First" to generate my database in a WPF application, but I'm not able to run the Database.SetInitializer anywhere in my WPF application. I'll get a VerificationException when the GUI is generated from the XAML code if I'm using Database.SetInitializer in the constructor or in the WPF Load event.

Have you succeed using Database.SetInitializer in an WPF application. I can't find any information about this on the Internet. All articles, examples and tutorials are based on APS applications.

Any advise?

Thanks!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.