Click here to Skip to main content
Click here to Skip to main content

Ensure Your Code First DB is Always Initialized

By , 27 Jun 2012
 

Introduction

With EF Code First, the built in DB Initializers, DropCreateDatabaseAlways, CreateDatabaseIfNotExists, and DropCreateDatabaseIfModelChanges, and any classes you derive straight from these, only invoke their Seed method when your DbContext based class needs to access the database. This can be frustrating, especially when you are debugging Seed methods and start an application merely to check DB initialization. This tip describes a very simple way to ensure your DB is always initialized before your client app even starts up, without having to write unwanted code in the client app.

How Do I Do This?

Simply invoke a data access method inside a static constructor for your DbContext derivative:

public class TheContext: DbContext
{
    static TheContext()
    {
        Database.SetInitializer(new DbInitAlways());
        var ctx = new TheContext();
        var r = ctx.Roles.First();
    }
    public DbSet<Role> Roles { get; set; }
}  

Points of Interest

  • The first line above, setting the initializer, should always be changed to set a suitable initializer. Using a DropCreateDatabaseAlways or derivative, like I have, will always drop the database. IT WILL ALWAYS DESTROY ANY TEST DATA YOU HAVE CAPTURED.
  • I just used Roles because it was a convenient and common DbSet on my DbContext. Use any available to you.
  • It is necessary to call First on Roles, and not just Roles, as the latter returns an IQueryable, which only accesses the DB when needed, that is, when iterated, or queried for a specific object.

License

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

About the Author

Brady Kelly
Founder Erisia Web Development
South Africa South Africa
Member
I am a software developer in Johannesburg, South Africa. I specialise in C# and ASP.NET, with SQL Server, with special fondness for MVC and jQuery. I am currently trying to learn WPF from the bottom up, and somehow find a way to resurrect my creative faculties.
- Follow me on Twitter at @bradykelly

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 27 Jun 2012
Article Copyright 2012 by Brady Kelly
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid