How DbMigrationsConfiguration is related to a DbMigration in EF

倾然丶 夕夏残阳落幕 提交于 2020-07-18 09:31:17

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/31267660/how-dbmigrationsconfiguration-is-related-to-a-dbmigration-in-ef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!