首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何先用代码在Entity Framework6.2中创建索引

如何先用代码在Entity Framework6.2中创建索引
EN

Stack Overflow用户
提问于 2014-03-25 02:58:29
回答 9查看 97.5K关注 0票数 122

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

EN

回答 9

Stack Overflow用户

发布于 2014-03-25 03:31:25

目前还没有用于通过fluent API创建索引的"first class support",但是您可以通过fluent API将属性标记为具有来自Annotation API的属性。这将允许您通过fluent接口添加Index属性。

以下是来自EF的Issues站点的工作项的一些示例。

在单个列上创建索引:

modelBuilder.Entity<MyEntity>()
    .Property(e => e.MyProperty)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(new IndexAttribute()));

单个列上的多个索引:

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

多列索引:

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

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

票数 87
EN

Stack Overflow用户

发布于 2015-03-22 11:57:58

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

安装EntityFramework.IndexingExtensions nuget包。

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

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

The project and source code are here。享受吧!

票数 36
EN

Stack Overflow用户

发布于 2016-05-02 22:19:46

如果没有明确的名称:

[Index]
public int Rating { get; set; } 

使用特定的名称:

[Index("PostRatingIndex")] 
public int Rating { get; set; }
票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22618237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档