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

Whether you work in SQL Server Management Studio or Visual Studio, Redgate tools integrate with your existing infrastructure, enabling you to align DevOps for your applications with DevOps for your SQL Server databases. Discover true Database DevOps, brought to you in partnership with Redgate.

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!

It’s easier than you think to extend DevOps practices to SQL Server with Redgate tools. Discover how to introduce true Database DevOps, brought to you in partnership with Redgate

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}