Reputation: 901
I'm using entity framework code first approach in my project. I've created model and enabled migrations using enable-migrations statement in package manager console. My context class contains mapping configurations and relationships like
modelBuilder.Configurations.Add(new PostMap());
modelBuilder.Configurations.Add(new UserMap());
Up method in my migration file 201302261054023_InitialCreate.cs contains all table definitions as my context specified via DbSet<Type> property.
I changed InitializeDatabase method in my custom database Initializer, because I want to migrate up to specific migration during database initialization.
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");
}
Is possible to modify Up method in 201302261054023_InitialCreate class to add another index from
CreateTable(
"dbo.City",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(maxLength: 450),
})
.PrimaryKey(t => t.Id);
to
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);
without appending another migration?
Upvotes: 0
Views: 877
Reputation: 901
After mining plenty of web pages related to migrations, I've found that modifying initial migration could help me only if I update database to "zero migration" (empty database). Without migration to zero database I could add another migration and create indexes in new migration like
public partial class InitialIndexes : DbMigration
{
public override void Up()
{
CreateIndex("City", "Name", true);
}
public override void Down()
{
DropIndex("City", new[] {"Name"});
}
}
Upvotes: 5
Reputation: 3390
To create an index you can use the ExecuteSqlCommand.
context.Database.ExecuteSqlCommand("CREATE INDEX IX_TableName_ColumnName ON TableName (ColumnName)");
I normally have this command in a Seed override method like the following.
protected override void Seed(YourContext context)
{
context.Database.ExecuteSqlCommand("CREATE INDEX IX_TableName_ColumnName ON TableName (ColumnName)");
//...Rest of seed code
}
You should be able to use the same call in your method.
Upvotes: 0