How to prevent the creation of EF4.1 from creating a database if it does not exist?

I am using EF4.1 with MVC3 and I need to override to prevent the creation of EF db if it does not exist. Instead of creating a new db, I would like to catch an error and report that the start directory (database name) is not valid in the connection string.

However, during development, I would like to allow updating for new classes / properties to create tables / columns in the database.

Is there a better way or sample here?

+4
source share
2 answers

In my application, I completely disabled the context initializer and handled the database mapping and schema manually.

For instance:

public class AppDbContext : DbContext { public IDbSet<Account> Accounts { get; set; } public AppDbContext() : base("connection_string") { Database.SetInitializer<AppDbContext>(null); // Important! Dont use entity framework initializer !important } protected override void OnModelCreating(DbModelBuilder modelBuilder) { /* Register custom mapping class */ modelBuilder.Configurations.Add(new AccountMapper()); base.OnModelCreating(modelBuilder); } } 

And user mapping:

 public class AccountMapper : EntityTypeConfiguration<Account> { /// <summary> /// Employee entity mapper /// </summary> public AccountMapper() { ToTable("accounts"); HasKey(x => x.Id); ... } } 
+3
source

I would suggest exploring the EF database initializer, in particular the IDatabaseInitializer interface.

If you just want to stop creating the database when it does not exist, just set the Initializer to null . But if you want to register an event or something along these lines, just create your own IDatabaseInitializer - it's not difficult.

You can then set the Application_Start initializer to your global.asax.cs file as follows:

 Database.SetInitializer(new YourCustomInitializer()); 

As a bonus, here is an example of the IDatabaseInitializer that I use to start database migration (using FluentMigrator ) ... it is extremely convenient if I say so myself!

 public class MigrationsDbContextInitializer : IDatabaseInitializer<YourDbContext> { private static readonly ILog Logger = LogManager.GetLogger(typeof(MigrationsDbContextInitializer)); public void InitializeDatabase(YourDbContext context) { var announcer = new BaseAnnouncer(x => Logger.Info(x)); var runnerContext = new RunnerContext(announcer) { Database = "sqlserver2008", Connection = context.Database.Connection.ConnectionString, Target = "YourEntitiesNamespace", PreviewOnly = false, Task = "migrate" }; new TaskExecutor(runnerContext).Execute(); } } 
+1
source

All Articles