如何首先使用代码在Entity Framework 6.2中创建索引

Val*_*alo 106 entity-framework ef-code-first entity-framework-6

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

Sco*_*ain 85

目前,通过流畅的API创建索引没有"第一类支持",但您可以通过流畅的API将属性标记为具有Annotation API的属性.这将允许您Index通过流畅的界面添加属性.

以下是来自EF的问题网站的工作项的一些示例.

在单个列上创建索引:

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute()));
Run Code Online (Sandbox Code Playgroud)

单个列上的多个索引:

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new[]
            {
                new IndexAttribute("Index1"),
                new IndexAttribute("Index2") { IsUnique = true }
            }));
Run Code Online (Sandbox Code Playgroud)

多列索引:

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty1)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName,
        new IndexAnnotation(new IndexAttribute("MyIndex", 1)));

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty2)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute("MyIndex", 2)));
Run Code Online (Sandbox Code Playgroud)

使用上述技术将导致.CreateIndex()在您Up()下一次迁移时为您的函数自动创建调用(如果您不使用迁移,则会在数据库中自动创建).

  • 我尝试了`HasAnnotation`方法,没有这样的方法.但是我找到了一个名为`HasColumnAnnotation`的方法,它接受你提供的参数.你需要更新你的答案还是我错了? (8认同)
  • 可能会在列上添加索引但不会删除在主键上创建的聚簇索引.hasKey在主键上创建聚簇索引,默认情况下不会删除.必须在`.Primarykey(x => x.id,clustered:false)`方法中通过声明clusered:false创建的迁移文件中明确删除 (4认同)
  • 请参阅今年早些时候设计会议中以下链接的底部:"将HasAnnotation重命名为HasColumnAnnotation(以及代码库中的其他相关位置)." http://entityframework.codeplex.com/wikipage?title=Design%20Meeting%20Notes%20%E2%80%93%20January%2016%2C%202014 (3认同)

ChW*_*ChW 73

那么26.10.2017实体框架6.2 正式发布.它包括通过Fluent API轻松定义索引的可能性.这是使用已经公布在6.2的测试版.

现在您可以使用该HasIndex()方法,IsUnique()如果它应该是唯一索引.

只是一个小比较(之前/之后)的例子:

// 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();
Run Code Online (Sandbox Code Playgroud)

也可以将索引标记为聚簇.IsClustered().


编辑#1

添加了多列索引的示例以及如何将索引标记为集群的其他信息.


编辑#2

作为附加信息,在EF Core 2.1中,它与EF 6.2中的完全相同.
是MS Doc artcile的参考.


Mat*_*int 36

我已经创建了一些扩展方法并将它们包装在nuget包中以使这更容易.

安装EntityFramework.IndexingExtensionsnuget包.

然后,您可以执行以下操作:

public class MyDataContext : DbContext
{
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Customer>()
        .HasIndex("IX_Customers_Name",          // Provide the index name.
            e => e.Property(x => x.LastName),   // Specify at least one column.
            e => e.Property(x => x.FirstName))  // Multiple columns as desired.

        .HasIndex("IX_Customers_EmailAddress",  // Supports fluent chaining for more indexes.
            IndexOptions.Unique,                // Supports flags for unique and clustered.
            e => e.Property(x => x.EmailAddress)); 
  }
}
Run Code Online (Sandbox Code Playgroud)

项目和源代码在这里.请享用!


Hug*_*rio 22

没有明确的名称:

[Index]
public int Rating { get; set; } 
Run Code Online (Sandbox Code Playgroud)

具有特定名称:

[Index("PostRatingIndex")] 
public int Rating { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • 这个问题包含以下语句`而不是使用新的IndexAttribute`你注意到了吗? (3认同)

小智 18

从EF 6.1开始,[Index]支持该属性.
使用[Index(IsUnique = true)]的唯一索引.
这是微软链接

public class User 
{ 
    public int UserId { get; set; } 

    [Index(IsUnique = true)] 
    [StringLength(200)] 
    public string Username { get; set; } 

    public string DisplayName { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

  • 字符串长度是必需的,否则您会看到“is 的类型不能用作索引中的键列”异常。我的同事更喜欢 Context 上的 modelBuilder 解决方案,这样你就不会弄乱你的 User 类,我想这是有效的。 (3认同)
  • 虽然这在理论上可以回答这个问题,但 [最好](​​//meta.stackoverflow.com/q/8259) 在此处包含答案的基本部分,并提供链接以供参考。 (2认同)

Gui*_*ira 8

实体框架6

Property(c => c.MyColumn)
        .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_MyIndex")));
Run Code Online (Sandbox Code Playgroud)

并添加使用:

using System.Data.Entity.Infrastructure.Annotations;
using System.ComponentModel.DataAnnotations.Schema;
Run Code Online (Sandbox Code Playgroud)


Emr*_*mre 7

您可以使用INDEX数据注释 代码优先数据注释

  • 对于nvarchar,最大密钥长度为900字节;对于varchar,最大密钥长度为450字节。如果首先使用代码,则字符串属性将为nvarchar,并且应包括属性[StringLength“,如[[StringLength(450)] (3认同)