How DbMigrationsConfiguration is related to a DbMi

2020-08-15 03:33发布

In Entity Framework by using Enable-Migrations a Migrations folder is created containing a Configuration inherited from DbMigrationsConfiguration like this:

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    ...
}

All the created migrations which are created using Add-Migration are placed in the Migrations folder too.

public partial class Init: DbMigration
{
    public override void Up()
    {
        ...
    }

    public override void Down()
    {
        ...
    }
}

I didn't find any code that relates these two together ( for example having a configuration property in migrations). The only relation I found is that both are placed in same folder. If I have more than 1 DbContext and consequently more than 1 Configuration, I'm wondering how these DbMigrations are distinguished?

Question: How DbMigration classes are related to a Configuration?

2条回答
Animai°情兽
2楼-- · 2020-08-15 04:09

When you run the update-database command, the database operations in the up() method in the latest DbMigration derived classes is performed. If that is successful, the commands in the Configuration class are executed. One of those methods is the seed() method where you can optionally add code to plug values into your tables after a migration. When you specify a target migration (presumably earlier than the latest), the migration works through the chain of down() methods in the migration classes to get to the version you wanted.

查看更多
贪生不怕死
3楼-- · 2020-08-15 04:12

They are related by convention. By default, it will store the migrations in a root folder called Migrations. You can override this in the constructor of the config (https://msdn.microsoft.com/en-us/library/system.data.entity.migrations.dbmigrationsconfiguration(v=vs.113).aspx) or when you enable-migrations:

public Configuration()
{
    AutomaticMigrationsEnabled = true;
    MigrationsDirectory = @"Migrations\Context1";
}

For multiple contexts, create a different config and folder for each by using -ContextTypeName ProjectName.Models.Context2 -MigrationsDirectory:Migrations\Context2. Here is a walkthrough: http://www.dotnettricks.com/learn/entityframework/entity-framework-6-code-first-migrations-with-multiple-data-contexts

查看更多
登录 后发表回答