【问题标题】:Is it possible to append indexes modifying initial migration?是否可以附加索引来修改初始迁移?
【发布时间】:2013-02-26 13:47:07
【问题描述】:

我在我的项目中使用实体框架代码优先方法。我已经使用包管理器控制台中的 enable-migrations 语句创建了模型并启用了迁移。我的上下文类包含映射配置和关系,如

modelBuilder.Configurations.Add(new PostMap());
modelBuilder.Configurations.Add(new UserMap());

我的迁移文件 201302261054023_InitialCreate.cs 中的 Up 方法包含所有表定义作为我通过 DbSet 属性指定的上下文。

我在自定义数据库 Initializer 中更改了 InitializeDatabase 方法,因为我想在数据库初始化期间向上迁移到特定迁移。

public void InitializeDatabase(T context)
{
    bool databaseExists = context.Database.Exists();
    if (!databaseExists)
        context.Database.CreateIfNotExists();

    var configuration = new Configuration();
    var migrator = new DbMigrator(configuration);
    migrator.Update("InitialCreate");
}

可以修改 201302261054023_InitialCreate 类中的 Up 方法来添加另一个索引

CreateTable(
        "dbo.City",
        c => new
            {
                Id = c.Int(nullable: false, identity: true),
                Name = c.String(maxLength: 450),
            })
        .PrimaryKey(t => t.Id);

CreateTable(
        "dbo.City",
         c => new
            {
                Id = c.Int(nullable: false, identity: true),
                Name = c.String(maxLength: 450),
            })
        .PrimaryKey(t => t.Id)
        .Index(t=>t.Name,true);

不附加另一个迁移?

【问题讨论】:

    标签: entity-framework ef-code-first entity-framework-5 entity-framework-migrations


    【解决方案1】:

    在挖掘了大量与迁移相关的网页后,我发现只有将数据库更新为“零迁移”(空数据库),修改初始迁移才能对我有所帮助。如果不迁移到零数据库,我可以添加另一个迁移并在新迁移中创建索引,例如

    public partial class InitialIndexes : DbMigration
    {
        public override void Up()
        {
            CreateIndex("City", "Name", true);
        }
    
        public override void Down()
        {
            DropIndex("City", new[] {"Name"});
        }
    }
    

    【讨论】:

      【解决方案2】:

      要创建索引,您可以使用 ExecuteSqlCommand。

      context.Database.ExecuteSqlCommand("CREATE INDEX IX_TableName_ColumnName ON TableName (ColumnName)");
      

      我通常在种子覆盖方法中使用此命令,如下所示。

                  protected override void Seed(YourContext context)
                  {
                      context.Database.ExecuteSqlCommand("CREATE INDEX IX_TableName_ColumnName ON TableName (ColumnName)");
                      //...Rest of seed code
                   }
      

      您应该能够在您的方法中使用相同的调用。

      【讨论】:

      • 古伯,谢谢您的回答。我的问题没有得到适当的描述。我想使用迁移来管理索引。您的方法应该是有效的,但仅在数据库迁移到最新版本的情况下。我需要使用迁移到比最新版本旧的数据库创建索引。
      猜你喜欢
      • 2015-12-27
      • 2017-04-03
      • 2018-07-29
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多