1

I am creating a model with EF4.1 CodeFirst. I use:

Database.SetInitializer(Of dbModel.dbDB2Data)(New DropCreateDatabaseIfModelChanges(Of dbModel.dbDB2Data))

And

MyBase.Database.ExecuteSqlCommand("CREATE INDEX IX_EXPLAN ON DBO.EXPLANS (PROGNAME, BIND_TIME, ACCESSNAME)")

to create an index. The problem is, if I put the ExecuteSqlCommand in the DbContext New subroutine, it executes everytime the application is started, even if the DB already exists, and then an error occures because the index already exists. If I put it in the OnModelCreating event, I get the following error:

The context cannot be used while the model is being created.

So how can I have the ExecuteSqlCommand do its thing only when the DB is being created?

GilShalit
  • 6,175
  • 9
  • 47
  • 68
  • This is ominous - question up-voted 5 minutes after being posted. If it's so good does it mean there is no good answer? – GilShalit Nov 09 '11 at 11:56

1 Answers1

0

You need to create custom database initializer and execute your SQL command in the Seed method of the initializer. The initializer is called only once when the database is created. Here is similar example with unique index.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670