我遇到EF CodeFirst方法的问题。我需要在创建数据库后创建索引。但是OnModelCreating方法太早调用(DB尚不存在)。有没有“AfterModelCreating”方法?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
this.Database.ExecuteSqlCommand(String.Format("CREATE INDEX IX_{0} ON {1} ({0})", "Text", "Table"));
}
由于
答案 0 :(得分:1)
在4.3之前的EF版本中,您应配置数据库初始化程序
System.Data.Entity.Database.SetInitializer<YourDbContext>(new YourDbInitializer());
初始化类可能如下所示:
public class YourDbInitializer : DropCreateDatabaseIfModelChanges<YourDbContext>
{
protected override void Seed(DiorContextBase context)
{
context.Database.ExecuteSqlCommand(
"CREATE UNIQUE NONCLUSTERED INDEX Username_Unique " +
"ON dbo.Users(username)");
}
}
在最新的EF版本中,使用迁移http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx