is it possible to use sql files as EF database migrations?

时间:2015-10-06 09:01:33

标签: c# entity-framework database-migration database-project

I'm using EF6.0 and implementing my db with SQLServerDatabaseProject. I want to use the EF Migration tools for Database migration. but since I have my database on DbProject I want all my migration files to be SQLFiles (not c#) So I would like to know if EF supports this feature and if not, is it possible to write a new Migration class which keeps the EF features but works this way?

Please also consider that I don't want EF to generate my migrations but I would like to be able to use other migration commands such as update-database and ...

==MORE DETAILS ABOUT THE QUESTION==

I don't want to have c# classes load my sql files. The sql files must be saved for up and down migrations directly and be treated exactly as if they are the DbMigration classes. A simple example of Migrations dir would be something like this:

Migrations 
   -> up
       -> 201510060807125_alter-course-change-family.sql
       -> 201510060813136_alter-course-add-mark-column.sql
   -> down
       -> 201510060807125_alter-course-change-family.sql
       -> 201510060813136_alter-course-add-mark-column.sql

2 个答案:

答案 0 :(得分:5)

只需在迁移课程中使用SqlFile扩展方法:

public partial class MyFancyMigration : DbMigration
{
    public override void Up()
    {
        SqlFile("myUpSQLFile.sql");
    }

    public override void Down()
    {
        SqlFile("myDownSQLFile.sql");
    }
}

答案 1 :(得分:-1)

虽然您可以使用SqlFile方法,但我建议您在迁移文件夹中Seed文件的Configuration.cs方法上写一下。

internal sealed class Configuration : DbMigrationConfiguration<YourDbContext>
{
    protected override void Seed(YourDbContext context)
    {
        base.Seed(context);
        context.Database.ExecuteSqlCommand(FileReadAllText("migration.sql"));
    }
}

如果您使用Up方法编写迁移。当您更新数据库时,它将按照每次迁移执行,我认为您不会期望。

您想要的是每个Update-Database运行您的脚本。 (不是每次迁移)