Entity Framework 索引

栏目: ASP.NET · 发布时间: 4年前

内容简介:Entity Framwework 6 设置和使用索引,是一个比较 egg 疼的事情,为什么这么说呢?因为Entity Framwework 6的不同版本有不同的设置和使用方法,按照版本来划分,有三种方法:EF6中设置索引比较麻烦,我们需要先进行code first 迁移,然后在迁移类中的在

Entity Framwework 6 设置和使用索引,是一个比较 egg 疼的事情,为什么这么说呢?因为Entity Framwework 6的不同版本有不同的设置和使用方法,按照版本来划分,有三种方法:

  1. EF6 方法
  2. EF6.1.x方法
  3. EF6.2.x方法

EF6

EF6中设置索引比较麻烦,我们需要先进行code first 迁移,然后在迁移类中的 Up 方法中输入如下代码:

//创建索引且值唯一
CreateIndex("dbo.User","Name",unique:true);
//创建复合索引,索引名称为 **NameAndIdNumber**
CreateIndex("dbo.User",new []{"Name","IdNumber"},name:"NameAndIdNumber");

Down 方法中输入如下代码:

DropIndex("dbo.User","Name");
DropIndex("dbo.User",new []{"Name","IdNumber"});

注:EF6中通过迁移类创建的索引无法重命名

EF6.1.x

该版本定义索引的方法如下:

public virtual void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().Property(p => p.Name).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute()
    {
      IsUnique=true
    }));
}

上面这段代码的意思是,给User表创建一个唯一索引Name。同样上面的代码也可以单独定义在一个类中:

public class UserMap : EntityTypeConfiguration<User>
{
  public UserMap()
  {
      Property(p => p.Name).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() {
          IsUnique=true
      }));
  }
}

我们前面知道在EF6中创建的索引无法重命名,那么在EF6.1.x中创建的索引是否可以重命名吗?答案是当然可以,我们只需在前一类中的 UpDown 方法写入如下代码即可:

public override void Up()
{
    RenameIndex(table:"db.User",name:"Name",newName:"NameIndex");
}

public override void Down()
{
  RenameIndex(table:"db.User",name:"NameIndex",newName:"Name");
}

EF6.2.x

在EF6.2.X中创建索引比较简单,只需要调用 HasIndex 方法即可。

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {

        HasIndex(p=>p.Name);
        //创建复合索引
        HasIndex(p=>new {
          Name=p.Name,
          IdNumber=p.IdNumber
        });
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

An Introduction to the Analysis of Algorithms

An Introduction to the Analysis of Algorithms

Robert Sedgewick、Philippe Flajolet / Addison-Wesley Professional / 1995-12-10 / CAD 67.99

This book is a thorough overview of the primary techniques and models used in the mathematical analysis of algorithms. The first half of the book draws upon classical mathematical material from discre......一起来看看 《An Introduction to the Analysis of Algorithms》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具