No initial create with Entity Framework migrations

后端 未结 6 1854
梦如初夏
梦如初夏 2021-01-30 09:13

I\'m trying to get Entity framework migrations working. I\'ve enabled code first migrations, its created a migrations folder, config file and the mig history table, but no initi

相关标签:
6条回答
  • The article / tutorial here here (on microsoft.com) describes the reason that an initialCreate migration doesn't exist. The migration will only be added if the Database already exists. Otherwise, the first migration will be the 'initialCreate' as there is no point in creating a migration to a Database that doesn't exist yet... no DB means there is nothing to roll back to, on a down migration.

    Here is the pertinent paragraph:

    Run the Enable-Migrations command in Package Manager Console This command has added a Migrations folder to our project, this new folder contains two files:

    The Configuration class. This class allows you to configure how Migrations behaves for your context. For this walkthrough we will just use the default configuration. Because there is just a single Code First context in your project, Enable-Migrations has automatically filled in the context type this configuration applies to.

    An InitialCreate migration. This migration was generated because we already had Code First create a database for us, before we enabled migrations. The code in this scaffolded migration represents the objects that have already been created in the database. In our case that is the Blog table with a BlogId and Name columns. The filename includes a timestamp to help with ordering.

    If the database had not already been created this InitialCreate migration would not have been added to the project. Instead, the first time we call Add-Migration the code to create these tables would be scaffolded to a new migration.

    0 讨论(0)
  • 2021-01-30 09:46

    I know this is old, but there is no accepted answer and I had same issue.

    The trick is Enable-Migrations command. As stated here there is a command Enable-Migrations –EnableAutomaticMigrations. What it does it starts migrations exactly where you are.

    If you want the first migration to be creation of database, just run Enable-Migrations (without --EnableAutomaticMigrations).

    And remember to set initializer:

                Database.SetInitializer(new MigrateDatabaseToLatestVersion<LicenseContext, Configuration>());
    
    0 讨论(0)
  • 2021-01-30 09:55

    Not sure it's the same but I had a similar issue. I think my problem was related to the fact that I dont use a connections string from the config file to get my connection string.

    Fiddling with the start up project in the solution and also the projet combo in the Package Manager Console I was able to generate that first migration.

    Also make shure you have a connections string with the name of your dbContext class so the Package Manager can find it.

    0 讨论(0)
  • 2021-01-30 09:55

    I am using EF 6 RC1 and ran into this problem where neither the InitialCreate nor __MigrationHistory were being created when running Enable-Migrations.

    Actually, just after upgrading from EF 5 to EF 6 I ran Enable-Migrations and for some reason it created a __MigrationHistory table using the EF 5 schema, so I deleted it and my Migrations directory and tried to start over.

    But every time I deleted the Migrations directory it wouldn't create an InitialCreate or __MigrationHistory. I tried dropping and recreating the database and restarting Visual Studio 2012 to no avail. I gave up for the day and the next morning tried again - after letting my computer sit for about 8 hours it then created the InitialCreate. I am guessing there must be a cache somewhere that has a really long timeout - anyone? I am also guessing that rebooting might clear the cache, but I didn't try that.

    Whatever the case, it is possible to use PM> Add-Migration InitialCreate to do that step manually.

    Anyway, I still didn't get a __MigrationHistory table. Apparently, EF 6 has changed from creating it during the Enable-Migrations command to instead only creating it during the Update-Database command. And since my schema had already been created at that point, I needed to tear it down and recreate it manually:

    PM> Update-Database -TargetMigration:0
    PM> Update-Database
    

    I also stopped after the first command to check the state of the database to ensure I was updating the correct one, since according to this, the database connection string is picked up or autogenerated depending on the configuration, and unless it is configured right, there is no guarantee you are going to access the database or instance of SQL Server you intend to.

    After running both commands it created a __MigrationHistory table - and it didn't create it as a system table (which I didn't really want anyway), so all is good. Not exactly the same problem as the OP, but hopefully this will be helpful to someone else.

    References:

    • http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/
    • Reset Entity-Framework Migrations
    • How to recreate migrations from scratch
    0 讨论(0)
  • 2021-01-30 09:56

    This behavior is not in place by default, but it is available to you easily in many different forms.

    1. You can call context.Database.CreateIfNotExists(); at application startup.

    2. You can use one of the built-in DatabaseInitializers. The CreateDatabaseIfNotExists initializer is built into EntityFramework and just needs to be added to your project.

    3. You could create your own custom database initializer which includes option #1 inside of itself. Example: Code First Migrations and initialization

    You can include DatabaseInitializers in your project either by code or via a config file.

    Include an EntityFramework Database Initializer via code:

    In your application startup you can setup the DatabaseInitializer like so:

    System.Data.Entity.Database.SetInitializer<DairyMmmContext>(new System.Data.Entity.CreateDatabaseIfNotExists<DairyMmmContext>());
    

    NOTE: this code has changed multiple times throughout the life of entityframework! This example is for EF 4.3 which is the current production release available via nuget.

    Include an EntityFramework Database Initializer via configuration element:

    <configuration>
      <entityFramework>
        <contexts>
          <context type="MyNamespace.MyEFDataContext, AssemblyName">
            <databaseInitializer
              type="System.Data.Entity.CreateDatabaseIfNotExists`2[[MyNamespace.MyEFDataContext, AssemblyName],
                   [MyNamespace.Migrations.Configuration,  AssemblyName]], EntityFramework" />
          </context>
        </contexts>
      </entityFramework>
    </configuration>
    

    You'll notice this can be a little "ungraceful" with this configuration. You need to replace AssemblyName above with the name of the assembly you keep your entityframework stuff in, replace MyNamespace.MyEFDataContext with the fully qualified name of your entityframework data context, and replace MyNamespace.Migrations.Configuration with the fully qualified name to your configuration class (by default in the Migration folder inside your project).

    EDIT: Edited to respond to additional comments

    A migration is a change from one schema definition to another schema definition. Creating the empty database is not a migration (but everything after that is). There will be no migration source file in your project for just creating an empty db, that is done in code by the initializer.

    If you are already using the DropCreateDatabaseAlways initializer it should be doing that. However, I noticed you are setting the initializer in code which means there is the opportunity for a timing problem (setting the initializer after your context is already past the point of calling any initializers).

    You can force entityframework to run your initializer at any point in code with context.Database.Initialize(true); (The parameter is a true/false to force the initialization regardless of the current state). That would drop and recreate your database every time.

    But you can also just make sure your initializer is setup as early as possible in your application's life cycle (before you have created a single instance of your context).

    0 讨论(0)
  • 2021-01-30 09:58

    "Initial Create" is NOT created automatically! You need to create that yourself. Some tutorials of EF are confusing and I had the same misunderstanding as you.

    What you need to do:

    -Add-Migration InitialModel
    

    If you already have created your database tables and domain model, then:

    -Add-Migration InitialModel -IgnoreChanges
    

    From this point, your code will be in sync with database. Anytime you change the code, you can use Add-Migration to add the changes to your database.

    0 讨论(0)
提交回复
热议问题