4

從EF6.1,我們有一個屬性如何創建一個聚集索引與實體框架的核心

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

指定一個聚集索引的一種方式,但這種指數屬性似乎不是在EF核心權利現在?或者EF Core的實現方式是什麼?謝謝。

+0

樣本見https://www.learnentityframeworkcore.com/configuration/fluent- api/hasindex-method –

回答

11

從目前EF核心文檔 - Indexes部:不能使用數據的註釋來創建

數據註釋

指標的影響。

但是可以肯定的,你可以指定通過流利的API(注意有ForSqlServer前綴擴展方法,這似乎表示SqlServer的特定功能):

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

是否有用於'.ForSqlServerIsClustered();'的MySql特定版本? – Zze

+1

@Zze由於每個提供的都添加了自己的擴展方法,並且目前有[多個用於EF Core的MySql提供程序](https://docs.microsoft.com/en-us/ef/core/providers/),因此您應該檢查你正在使用的一個。我會檢查使用'ForMySql'的擴展方法。 –

0

在沒有內置支持,你可以使用自定義屬性自己的註釋模特屬性和適用於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; 
      } 
     } 
    } 
} 

有了一個簡單的標記屬性類:

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

然後在您的模型類,只需添加屬性來創建一個輔助指標:流利的API用於索引

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