How to create a Clustered Index with Entity Framework Core

前端 未结 4 626
广开言路
广开言路 2020-12-10 12:53

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 U         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 13:21

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

提交回复
热议问题