简答: Entity Framework 6 不允许具有不同排序的多个索引。
长答案:可能无法直接做到这一点,但可以通过一些调整来实现。经过大量阅读,我发现创建一个继承IndexAnnotation的新类并添加SortOrder属性会非常复杂。
我发现实现这一点的最简单方法是查看我可以调整哪些现有属性以实现多索引排序。使用 Name 属性可以做到这一点,因为它是一个字符串。可以直接在名称中添加排序索引,稍后生成SQL代码时截取。
假设我需要像这样索引属性:
- 类型 (ASC)
- DateFor (Desc)
- 创建日期(Desc)
然后我将命名我的索引,后跟分隔符 (:) 和排序顺序。它看起来像这样:
var indexName = "IX_Table:ASC,DESC,DESC";
具有多个字段的索引如下所示:
this.Property(t => t.Type)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new[]
{
new IndexAttribute(indexName) { Order = 1 }
}
)
);
this.Property(t => t.DateFor)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new[]
{
new IndexAttribute(indexName) { Order = 2 }
}
)
);
this.Property(t => t.DateCreated)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new[]
{
new IndexAttribute(indexName) { Order = 3 }
}
)
);
我们现在必须创建一个自定义 SQL 生成类,以便生成正确的 SQL 代码来解析我们的“调整”索引名称:
public class CustomSqlServerMigrationSqlGenerator : SqlServerMigrationSqlGenerator
{
protected override void Generate(CreateIndexOperation createIndexOperation)
{
using (var writer = Writer())
{
writer.Write("CREATE ");
if (createIndexOperation.IsUnique)
{
writer.Write("UNIQUE ");
}
if (createIndexOperation.IsClustered)
{
writer.Write("CLUSTERED ");
}
else
{
writer.Write("NONCLUSTERED ");
}
string name = createIndexOperation.Name;
string[] sorts = {};
if (createIndexOperation.Name.Contains(":"))
{
var parts = createIndexOperation.Name.Split(':');
if (parts.Length >= 1)
{
name = parts[0];
}
if (parts.Length >= 2)
{
sorts = parts[1].Split(',');
}
}
writer.Write("INDEX ");
writer.Write(Quote(name));
writer.Write(" ON ");
writer.Write(Name(createIndexOperation.Table));
writer.Write("(");
// Add the columns to the index with their respective sort order
string fields = "";
if (sorts.Length == 0 || sorts.Length == createIndexOperation.Columns.Count)
{
for (int i=0 ; i<createIndexOperation.Columns.Count ; i++)
{
string sort = "ASC";
if (sorts.Length == 0)
{
// Do nothing
}
else if (sorts[i] != "ASC" && sorts[i] != "DESC")
{
throw new Exception(string.Format("Expected sort for {0} is 'ASC' or 'DESC. Received: {1}", name, sorts[i]));
}
else
{
sort = sorts[i];
}
fields = fields + Quote(createIndexOperation.Columns[i]) + " " + sort + ",";
}
fields = fields.Substring(0, fields.Length - 1);
}
else
{
throw new Exception(string.Format("The sort (ASC/DEC) count is not equal to the number of fields in your Index ({0}).", name));
}
writer.Write(fields);
writer.Write(")");
Statement(writer);
}
}
}
最后,您需要通过编辑 Configuration.cs 文件来告诉 Entity Framework 使用您的新代码生成方法而不是默认方法:
internal sealed class MyConfiguration : DbMigrationsConfiguration<MyContext>
{
/// <summary>
/// Constructor
/// </summary>
public MyConfiguration()
{
// Other stuff here...
// Index/Unique custom generation (Ascending and Descending)
SetSqlGenerator("System.Data.SqlClient", new CustomSqlServerMigrationSqlGenerator());
}
}
就是这样。它可能不是最干净的解决方案,但如果您动态生成实体(如我所做的那样),您将节省大量时间并避免忘记运行原始 SQL。
See the code here
非常感谢Rowan Miller 和他博客上的所有文章。这个答案的灵感来自:Customizing Code First Migrations Provider。