Entity Framework 6.1 では、新しいHasColumnAnnotation
メソッドを介してテーブル インデックスを作成する機能が追加されたようです。プロセスを高速化するために、いくつかのヘルパー拡張機能を作成しました。
public static class MappingExtensions
{
public static StringPropertyConfiguration HasIndex(this StringPropertyConfiguration config, bool isUnique = false)
{
return config.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = isUnique }));
}
public static StringPropertyConfiguration HasIndex(this StringPropertyConfiguration config, string name, int order = 1, bool isUnique = false)
{
return config.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute(name, order) { IsUnique = isUnique }));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration config, bool isUnique = false)
{
return config.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = isUnique }));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration config, string name, int order = 1, bool isUnique = false)
{
return config.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute(name, order) { IsUnique = isUnique }));
}
}
これはうまく機能します...別のインデックスで既に使用されている列を含む2番目のインデックスを作成しようとするまで。最後に追加したものは、オリジナルを上書きします。とHasColumnAnnotation
で利用可能な新しいものを介して、同じ列に複数のインデックスを現在追加できるかどうかを知っている人はいますか?StringPropertyConfiguration
PrimitivePropertyConfiguration
移行スクリプトに手動でインデックスを追加することで、いつものようにこれを回避できますが、EntityTypeConfiguration
マッピングでこれを構成できると、すべてを 1 か所にまとめることができます。
Gerts のフィードバックの後、これが私が最終的に行ったことです。
public static class MappingExtensions
{
public static StringPropertyConfiguration HasIndex(this StringPropertyConfiguration config, params IndexAttribute[] indexes)
{
return config.HasColumnAnnotation("Index", new IndexAnnotation(indexes));
}
public static PrimitivePropertyConfiguration HasIndex(this PrimitivePropertyConfiguration config, params IndexAttribute[] indexes)
{
return config.HasColumnAnnotation("Index", new IndexAnnotation(indexes));
}
}
そして、ここに新しい使い方があります:
Property(x => x.Name).IsRequired().HasMaxLength(65).HasIndex(new IndexAttribute("IX_Countries_Name") { IsUnique = true }, new IndexAttribute("IX_Countries_Published", 2))