How to create a Clustered Index with Entity Framework Core

拜拜、爱过 提交于 2019-11-30 03:32:25

问题


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; }
}

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


回答1:


From the current EF Core documentation - Indexes section:

Data Annotations

Indexes can not be created using data annotations.

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();



回答2:


In the absence of built-in support, you can use a custom attribute of your own to annotate model properties and apply in OnModelCreating():

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var prop in entity.GetProperties())
        {
            var attr = prop.PropertyInfo.GetCustomAttribute<IndexAttribute>();
            if (attr != null)
            {
                var index = entity.AddIndex(prop);
                index.IsUnique = attr.IsUnique;
                index.SqlServer().IsClustered = attr.IsClustered;
            }
        }
    }
}

With a simple marker attribute class:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class IndexAttribute : Attribute
{
    public bool IsUnique { get; set; } 
    public bool IsClustered { get; set; } 
}

Then in your model class, just add the attribute to create a secondary index:

public class User
{
    public int UserId { get; set; }
    [Index(IsUnique = true, IsClustered = true)]
    public string Nickname { get; set; }
}



回答3:


Or this works too, say if you wanted to cluster by age...

            modelBuilder
            .Entity<Person>()
            .Property(t => t.Age)
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsClustered = true}));


来源:https://stackoverflow.com/questions/38944128/how-to-create-a-clustered-index-with-entity-framework-core

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