Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Entity Framework Code First Tips and Tricks

DZone's Guide to

Entity Framework Code First Tips and Tricks

· Database Zone
Free Resource

Learn how to move from MongoDB to Couchbase Server for consistent high performance in distributed environments at any scale.

These days I do all of my development work with EF code first. One of the cool things about EF is its ability to drop and recreate the database when the models change. This is great when you are trying to associate your source code with a particular revision of the database schema. However, dropping and recreating a database on a production or staging environment can have some serious repercussions. Therefore, I like to put some safeguards in place to make sure that this only happens under the right conditions. 

Please keep in mind that the newest version of EF has migration support! So you can alter the database instead of dropping and recreating it. However, if you use the DropRecreateDatabaseIfModelChanges feature of EF then you may find the following tip useful.

Safeguarding from an Accidental Drop/Recreate

In wrap the code that sets up the EF Context initializer with the following helper method which determines whether or not I am in development mode. For me, development mode means I have the debugger attached or I am working with a local SQL instance:

static bool InDevelopmentMode {
    get {    
        if (System.Diagnostics.Debugger.IsAttached) return true;
        if (Environment.UserName.ToUpper().Contains("<YOUR ID HERE>")) return true;    

        var connectionString = ConfigurationManager.ConnectionStrings["MyDbContext"].ConnectionString;
        var csb = new SqlConnectionStringBuilder(connectionString);
        return csb.DataSource.Equals("."); //shorthand for localhost                
    }
}

Now we can leverage the method to conditionally execute the DB initializer:

if (InDevelopmentMode) {
    Database.SetInitializer(new MyContextInitializer()); //Register the EF context initializer
}

Disabling EF Migrations

As I mentioned earlier, the latest version of EF has migration support. By default, migrations will be enabled. If you want to disable it you can do the following:

Create a Migrations Configuration class

using System.Data.Entity.Migrations;

namespace MyApp.Domain.DataContext {
    public sealed class MyContextConfiguration : DbMigrationsConfiguration<MyContext> {
        public MyContextConfiguration() {
            AutomaticMigrationsEnabled = false;
        }
    }
}

Bootstrap it!

For web apps this would add this code to the Global.asax.cs and in WPF apps you would do this in App.xaml.cs...

new DbMigrator(new MSRContextConfiguration()); //migrations are disabled   
 

Happy Coding!

Want to deliver a whole new level of customer experience? Learn how to make your move from MongoDB to Couchbase Server.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}