开发者

How to prevent EF4.1 from creating a DB if it doesn't exist?

开发者 https://www.devze.com 2023-03-30 04:25 出处:网络
I\'m using EF4.1 with MVC3 and I need an override to prevent EF from creating a db if it doesn\'t exist. Instead of creating a new db I would like to catch the error and report that the initial catalo

I'm using EF4.1 with MVC3 and I need an override to prevent EF from creating a db if it doesn't exist. Instead of creating a new db I would like to catch the error and report that the initial catalog (the database name) is invalid in the connect string.

However, during development I would like to allow for updates for new classes/properties to create according table开发者_JS百科s/cols in the database.

Is there a best practice or pattern here?


In my application i am completly disable context initializer and handle database mapping and schema manually.

For example :

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 custom mapping :

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


I would suggest looking into the EF database initializer, specifically the IDatabaseInitializer interface.

If you just want it to stop creating the database when it doesn't exist, then just set the Initializer to null. But if you want to log the event or something along those lines then simply create your own IDatabaseInitializer - it's not hard.

You can then set the initializer Application_Start in your global.asax.cs like so:

Database.SetInitializer(new YourCustomInitializer());

As a bonus, here's an example IDatabaseInitializer that I use to run database migrations (using FluentMigrator)... it's extremely handy if I do 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();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消