问题描述
有没有办法使用代码优先在属性/列上创建索引,而不是使用新的 IndexAttribute
?
Is there a way to create an index on a property/column using code-first, instead of using the new IndexAttribute
?
推荐答案
嗯 26.10.2017 Entity Framework 6.2 是 正式发布.它包括一个可能性,可以通过 Fluent API 轻松定义索引.使用它已经是 在 6.2 的测试版中宣布.
Well 26.10.2017 Entity Framework 6.2 was officially released.It includes a possibility to define indexes with ease via Fluent API. Ho it is to use was already announced in the beta of 6.2.
现在您可以使用 HasIndex()
方法,如果它应该是唯一索引,则可以使用 IsUnique()
.
Now you can use the HasIndex()
method, followed by IsUnique()
if it should be an unique index.
只是一个小比较(之前/之后)示例:
Just a small comparison (before/after) example:
// before
modelBuilder.Entity<Person>()
.Property(e => e.Name)
.HasColumnAnnotation(
IndexAnnotation.AnnotationName,
new IndexAnnotation(new IndexAttribute { IsUnique = true }));
// after
modelBuilder.Entity<Person>()
.HasIndex(p => p.Name)
.IsUnique();
// multi column index
modelBuilder.Entity<Person>()
.HasIndex(p => new { p.Name, p.Firstname })
.IsUnique();
也可以使用 .IsClustered()
将索引标记为聚簇.
It is also possible to mark the index as clustered with .IsClustered()
.
编辑#1
添加了多列索引的示例以及如何将索引标记为聚集的附加信息.
Added an example for multi column index and additional information how to mark an index as clustered.
编辑#2
作为附加信息,在 EF Core 2.1 中它与现在在 EF 6.2 中完全相同.
这里是 MS Doc 文章作为参考.
As additional information, in EF Core 2.1 it is exactly the same like in EF 6.2 now.
Here is the MS Doc artcile as reference.
这篇关于如何使用代码在 Entity Framework 6.2 中创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!