Entity Framework Code First Tips and Tricks
Join the DZone community and get the full member experience.
Join For FreeThese 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!
Opinions expressed by DZone contributors are their own.
Trending
-
Best Practices for Securing Infrastructure as Code (Iac) In the DevOps SDLC
-
Top Six React Development Tools
-
RAML vs. OAS: Which Is the Best API Specification for Your Project?
-
Which Is Better for IoT: Azure RTOS or FreeRTOS?
Comments