如何使用 Entity Framework Core 创建聚集索引 [英] How to create a Clustered Index with Entity Framework Core

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

问题描述

从 EF6.1 开始,我们有一种在属性上指定聚集索引的方法

From EF6.1, we have a way of specifying a clustered index on a property

public class Person 
{
  [Index(IsClustered = true, IsUnique = true)]
  public long UserName { get; set; }
}

但是这个 Index 属性现在似乎不在 EF Core 中?在 EF Core 中,您如何实现这一目标?

But this Index attribute does not seem to be in EF Core right now? In EF Core how do you achieve this?

推荐答案

来自当前的 EF Core 文档 - 索引部分:

From the current EF Core documentation - Indexes section:

数据注释

不能使用数据注释创建索引.

Indexes can not be created using data annotations.

但可以肯定的是,您可以通过 Fluent API 指定它(注意具有 ForSqlServer 前缀的扩展方法似乎表示 SqlServer 特定功能):

But for sure you can specify that via Fluent API (note the extension methods having ForSqlServer prefix which seem to denote SqlServer specific features):

modelBuilder.Entity<Person>()
    .HasIndex(e => e.UserName)
    .IsUnique()
    .ForSqlServerIsClustered();

更新:对于 EF Core 3.0+,该方法仅被称为 IsClustered:

Update: for EF Core 3.0+ the method is called just IsClustered:

modelBuilder.Entity<Person>()
    .HasIndex(e => e.UserName)
    .IsUnique()
    .IsClustered();

更新:从 EF Core 5.0 开始,有 Index 数据注释现在在索引文档链接中提到,但它不能用于指定数据库特定的属性,如集群(特定于 SqlServer),所以原始答案仍然适用.

Update: Starting with EF Core 5.0, there is Index data annotation now mentioned in the Indexes documentation link, but it can't be used to specify database specific attributes like clustered (SqlServer specific), so the original answer still applies.

这篇关于如何使用 Entity Framework Core 创建聚集索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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