How can Entity Framework Code First Create Index in Descendent order?

不羁岁月 提交于 2019-12-10 17:36:23

问题


In fluent API, we can specify an Index on a field:

var indexAttr = new IndexAttribute("IX_EmployeeNumber")
{
    IsClustered = true
};

Property(c => c.EmployeeNumber)
    .HasColumnAnnotation("Index", new IndexAnnotation(indexAttr ))
    .HasMaxLength(8)
    .IsRequired();

After Add-Migration, we will get this CreateIndex statement:

CreateIndex("dbo.Employees", "EmployeeNumber", clustered: true, name: "IX_EmployeeNumber");

After a Update-Database, we have a sql like this:

CREATE CLUSTERED INDEX [IX_EmployeeNumber] ON [dbo].[Employees]
(
    [EmployeeNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

My question is: how can I create this index in descendent order? Something like:

CREATE CLUSTERED INDEX [IX_EmployeeNumber] ON [dbo].[Employees]
(
    [EmployeeNumber] DESC

I couldn't find related parameters in CreateIndex. Is it possible to be achieved in Code First migration?

Of course we know we could get everything working with DbMigration.Sql(...some sql statement...). But, how can we obtain the desired result with CreateIndex()?


回答1:


Take a look at how to customize code first migrations from the blog of Rowan Miller (one of the Entity Framework program managers).

This describes how to override the SqlServerMigrationsSqlGenerator sql generator to allow custom arguments to affect the generated sql.

As it happens, the scenario he walks through is extending the default behaviour of the CreateIndex migration operation to support specifying the creation of a descending index.

However, I don't think it is possible to expose this extension point to your code-first domain model creation code.




回答2:


I wanted to do what you were asking but also do it with multiple columns and multiple orders.

Based on Matt Caton's answer and Rowan Miller blog, I was able to answer my own question and get a custom solution that works as generic as possible (knowing that you cannot extend Entity Framework classes easily to add properties that don't exist).

See this answer for the exact solution.



来源:https://stackoverflow.com/questions/25293161/how-can-entity-framework-code-first-create-index-in-descendent-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!