2016-08-19 95 views
0

我需要創建一個多列索引,像這樣:運行自定義腳本後,每代碼優先遷移

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 

我已經找到一些方法來做到這一點,但沒有什麼突出的一種方式得到完全上面的。有沒有辦法將自定義SQL作爲遷移的一部分,而無需手動執行add-migration並在其中添加代碼?

回答

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); 
    }