How can I disable migration in Entity Framework 6.0
Asked Answered
E

7

74

I'm trying to ignore the "Automatic" migration using Entity Framework 6.0 rc1. My problem is that I don't want this feature right now and every time that my application runs I can see all entity logs trying to create all tables.

Anticipate thanks.

Evacuee answered 6/9, 2013 at 21:55 Comment(2)
Have you tried disabling the database initializer by using Database.SetInitializer<TContext>(null)?Swift
Late note, but the title would be more accurate if you said "disable automatic migration", as opposed to code-based migrationsSeligmann
L
50

Try this:

internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
}

UPDATE:

You can also try this:

Database.SetInitializer<YourContextType>(new CreateDatabaseIfNotExists());
Lui answered 7/9, 2013 at 3:26 Comment(6)
Yes, now it's working. I guess I was doing something wrong. The problem was that I deleted my __migratioHistory table and all migration files. I did Database.SetInitializer(new NullDatabaseInitializer<EfContext>()); the same as Database.SetInitializer<TContext>(null) thanks guysEvacuee
Guys, I guess I was not clear in my question. I realize that my problem was that I have an abstract base class that inherits from DbContext, called DefaultDbContext. The problem was that I did Database.SetInitializer<DefaultDbContext>(null) but the correct way is Database.SetInitializer<ConcretClassA>(null). Thanks!Evacuee
The first answer seems to work for me. I'm using a case where I make small models with Code First for an existing DB that I'll never change. Thanks.Comment
As soon as you have enabled the Migrations (added the Configuration class) both of this solution will not prevent running the Migrations. AutomaticMigrationsEnabled = false - disables the automatic migration database WITH NO MIGRATIONS IN THE CODE. Moreover my expectation was to avoid the migration running with the CreateDatabaseIfNotExists initializer. I expected that EF will create a database based on the model without the Migrations. But both CreateDatabaseIfNotExists and MigrateDatabaseToLatestVersion act the same way in case existing the migrations.Gentianaceous
Please take a look at the blog: msdn.microsoft.com/en-us/en-en/magazine/dn818489.aspxGentianaceous
I placed the Database.SetInitializer<YourContextType>(new CreateDatabaseIfNotExists()); in an static constructor to ensure calling only once and to not be exposed outside my DLLFlyer
E
52

You can put this inside your entityFramework section of the app.config:

<contexts>
  <context type="YourNamespace.YourDbContext, YourAssemblyName" disableDatabaseInitialization="true"/>
</contexts>

This msdn page tells all about the Entity Framework Configuration Section.

Enamour answered 22/1, 2015 at 15:34 Comment(8)
This is a much better way to permanently disable the database initializationRuprecht
This page tells all about the Entity Framework Configuration Section: msdn.microsoft.com/en-us/data/jj556606Unimpeachable
what is app.config, do you mean web.config ?Mcardle
how I determine what is YourAssemblyName ?Mcardle
where in the configuration put this code ? into <configuration> section ?Mcardle
App.config or Web.config, whatever you are using. 'YourAssemblyName' is the name of the assembly where you have your DbContext. You can right-click on the project and check it under the 'Application' tab. You have to put it inside your 'entityFramework' section, under 'configuration'.Enamour
To disable the initialization, you have to set disableDatabaseInitialization to true, not false.Enamour
In a solution I have model project and web project (set as startup project). My EF is installed on the model project... but I have entityframework section on both App.config (model project) or Web.config (web project)... why? is that correct?Paigepaik
L
50

Try this:

internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
}

UPDATE:

You can also try this:

Database.SetInitializer<YourContextType>(new CreateDatabaseIfNotExists());
Lui answered 7/9, 2013 at 3:26 Comment(6)
Yes, now it's working. I guess I was doing something wrong. The problem was that I deleted my __migratioHistory table and all migration files. I did Database.SetInitializer(new NullDatabaseInitializer<EfContext>()); the same as Database.SetInitializer<TContext>(null) thanks guysEvacuee
Guys, I guess I was not clear in my question. I realize that my problem was that I have an abstract base class that inherits from DbContext, called DefaultDbContext. The problem was that I did Database.SetInitializer<DefaultDbContext>(null) but the correct way is Database.SetInitializer<ConcretClassA>(null). Thanks!Evacuee
The first answer seems to work for me. I'm using a case where I make small models with Code First for an existing DB that I'll never change. Thanks.Comment
As soon as you have enabled the Migrations (added the Configuration class) both of this solution will not prevent running the Migrations. AutomaticMigrationsEnabled = false - disables the automatic migration database WITH NO MIGRATIONS IN THE CODE. Moreover my expectation was to avoid the migration running with the CreateDatabaseIfNotExists initializer. I expected that EF will create a database based on the model without the Migrations. But both CreateDatabaseIfNotExists and MigrateDatabaseToLatestVersion act the same way in case existing the migrations.Gentianaceous
Please take a look at the blog: msdn.microsoft.com/en-us/en-en/magazine/dn818489.aspxGentianaceous
I placed the Database.SetInitializer<YourContextType>(new CreateDatabaseIfNotExists()); in an static constructor to ensure calling only once and to not be exposed outside my DLLFlyer
D
30

Via web.config see - https://msdn.microsoft.com/en-us/data/jj556606.aspx#Initializers

Via Code (oddly, MUCH simpler answer)

public class MyDB : DbContext
{
    public MyDB()
    {
        Database.SetInitializer<MyDB>(null);
    }
}

or in Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // ...

        Database.SetInitializer<MyDB>(null);

        /// ...

    }
}
Delaminate answered 23/1, 2016 at 16:43 Comment(9)
For Code First EF, this is the cleanest answer.Roxie
Don't put it in the constructor for the DbContextIsar
Where would you put it? Why not in the constructor? (real question, not sarcasm)Delaminate
What is Database namespace ?Mcardle
@AaronSherman instead of putting this in the constructor, it can be called at any point before creating MyDB, e.g. in Application_Start(). It's a static method used to configure the initializer used by Entity Framework, so it should be called before the DbContext is created.Forwardness
@Mcardle Database is in the System.Data.Entity namespace.Forwardness
Nulling the dbase initializer in the entity class constructor results in a much faster initial view generation as compared to setting the initializer to null after the db context is instantiated. In my app, I had 1-1/2 MINUTE delay in my first db query. Found / fixed a couple of independent associations and got down to 55 seconds. Setting the migrations initializer after instantiating the db context got the first call down to 15 seconds. Moving the nulling of the initializer to the entity class constructor reduced the first call delay to just a couple of seconds... voila!Kiarakibble
@IdahoB: I realize I'm a couple years late to the party.. but, you mention nulling the initializer in the entity class ctor is faster than nulling it after the dbcontext is instantiated. Clarification please: Are you talking about nulling the initializer in the POCO ctor? Or in the DbContext ctor?Amabel
Personally I find adding the SetInitializer to the static constructor of my DbContext classes the cleanest approach.Zilla
P
4

If you found this question hoping for a simple answer to disable migrations because you typed "Enable-Migrations" and now things aren't working the way you expected, like not running the seed method you thought it would run, then look in the solution explorer and delete the Migrations folder. That will stop the code from looking at the migrations config to find initialization code. To get the Migrations folder back, just run "Enable-Migrations" again.

Patter answered 10/4, 2017 at 18:14 Comment(1)
also you can run Enable-Migrations -ForcePaigepaik
B
3

The mistake I was making was to call Database.SetInitializer(null); too late (after the context had been initialised). The best way to ensure migrations are disabled is to make the above call for all your contexts in your application startup. I favor this approach over setting it in the app.config so I can use my container to locate my contexts and then construct a call.

var migrationsMethod = typeof(System.Data.Entity.Database).GetMethod("SetInitializer");
foreach (var contextType in allContextTypes)
{
    migrationsMethod.MakeGenericMethod(contextType).Invoke(null, new object[] { null });                            
}
Boney answered 30/5, 2015 at 11:35 Comment(2)
Curious, how are you getting allContextTypes?Isar
Also curious how do you query for all contextsCoptic
R
1

Disabling the automatic migration can also be configured during the invoke of the enable-migrations command (which creates the Configuration class), using the EnableAutomaticMigration parameter with a value of false:

enable-migrations -EnableAutomaticMigration:$false -ContextTypeName FullyQualifiedContextName

The will create a Configuration class which sets the AutomaticMigrationsEnabled property to false, like in the answer above.


The EnableAutomaticMigration parameter of the enable-migrations command is mentioned in this article of the Entity Framework Tutorial page (however they use it with true which seems to be the default value).

Robinson answered 26/8, 2015 at 12:47 Comment(3)
EnableAutomaticMigration today is always false by defaultPaigepaik
what is the purpose of automatic migrations? it seems everyone hates themPaigepaik
An example of this part -ContextTypeName FullyQualifiedContextNamePaigepaik
G
1

Try this, Add this line in your MyContext class, this will be called before your MyContext constructor is called. This will stop creating the database as well as won't add tables into a connected database. Basically this line disables the default Code-First Database Initialization strategy which basically has a default strategy as CreateDatabaseIfNotExists.

static MyContext()
{
       System.Data.Entity.Database.SetInitializer<MyContext>(null);
}
Grim answered 27/9, 2019 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.