我不認爲有一個簡單的解決方案,但我有一個想法,你可以做什麼:創建一個自定義的遷移生成器。
遷移生成器是負責創建在遷移代碼文件中運行在數據庫上的SQL腳本的組件。我假設你有基於截圖的SQL Server。在這種情況下,您可以編寫自定義的SQL生成器,只需將覆蓋索引創建操作,這樣,如果該索引是非羣集,沒有數據被寫入到該腳本:
public class NoIndexGenerator : SqlServerMigrationSqlGenerator
{
protected override void Generate(CreateIndexOperation createIndexOperation)
{
if (!createIndexOperation.IsClustered)
{
return;
}
}
}
然後,你必須在註冊該組件該Configuration
類遷移:
internal sealed class Configuration : DbMigrationsConfiguration<MyCtx>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
// Add this line to register the sql generator
this.SetSqlGenerator("System.Data.SqlClient", new NoIndexGenerator());
}
}
現在,如果運行Add-Migration
,你就會有一個正常的遷移文件,並在它的CreateIndexOperation。但是如果運行Update-Database
,則不會創建非聚集索引。如果您運行Update-Database -Script
,也可以檢查此項。生成的腳本沒有非聚集索引。
如果你願意,你可以在管道中更高的位置,並創建一個定製的C#遷移腳手架。它應用了相同的邏輯SQL生成:
internal class NoIndexMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
protected override void Generate(CreateIndexOperation createIndexOperation, IndentedTextWriter writer)
{
if (!createIndexOperation.IsClustered)
{
return;
}
}
}
然後,您可以在Configuration
類這個樣子註冊:
internal sealed class Configuration : DbMigrationsConfiguration<MyCtx>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
// Add this line to register the C# code generator
this.CodeGenerator = new NoIndexMigrationCodeGenerator();
}
}
現在,如果你運行Add-Migration
,上的CreateIndex操作將消失生成的遷移cs文件也是如此。
我可能會使用第二種解決方案(可能會讓其他人閱讀代碼時看到在遷移cs文件中存在CreateIndex操作,但不在SQL腳本中),但最終它是您的選擇:)
如果必須,可以使用Generate()
方法的createIndexOperation
參數的其他屬性來實現更復雜的索引過濾。
如果您願意,也可以覆蓋具有DropCreateIndexOperation
類型參數的生成方法,但由於索引是以'drop-if-exists'模式丟棄的,所以我認爲這不是必需的。
首先,來看看這篇文章:?什麼時候的SQL Server停止把索引外鍵列(HTTP:// sqlskills。 com/BLOGS/KIMBERLY/post/When-did-SQL-Server-stop-puts-indexes-on-Foreign-Key-columns.aspx) 您可以編寫SQL查詢並在您的遷移中執行該查詢 – Saeed