每次代码优先迁移后运行自定义脚本

时间:2016-08-19 01:26:15

标签: entity-framework ef-code-first

我需要像这样创建一个多列索引:

CREATE NONCLUSTERED INDEX [IX_UserName_Inc_LastOnline_Lat_Long] ON [dbo].[User]
(
    UserName ASC
)
Include (LastOnline, Latitude, Longitude)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
GO

我已经找到了一些方法来做到这一点,但没有任何方法可以说明如何获得上述内容。有没有办法在不手动执行add-migration并在那里添加代码的情况下将自定义SQL作为迁移的一部分包含在内?

1 个答案:

答案 0 :(得分:0)

我决定将此作为Seed()方法的一部分运行:

protected override void Seed(AppContext context) {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<AppContext, Configuration>());

        if (!WebSecurity.Initialized) {
            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "User", "UserId", "Username", autoCreateTables: true);
        }

        context.Database.ExecuteSqlCommand(
            "IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_UserName_Inc_LastOnline_Lat_Long') " +
            "BEGIN " +
            " CREATE NONCLUSTERED INDEX [IX_UserName_Inc_LastOnline_Lat_Long] ON [dbo].[User] " +
            " (UserName ASC) " +
            " Include (LastOnline, LocationLat, LocationLong) " +
            " WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) " +
            "END"
        );

        base.Seed(context);
    }