如何首先使用代码在 Entity Framework 6.2 中创建索引 [英] How to create index in Entity Framework 6.2 with code first

查看:30
本文介绍了如何首先使用代码在 Entity Framework 6.2 中创建索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用代码优先在属性/列上创建索引,而不是使用新的 IndexAttribute ?

Is there a way to create an index on a property/column using code-first, instead of using the new IndexAttribute ?

推荐答案

Well 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 中创建索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆