1

I'm migrating my project from database-first to code-first.

Entity Framework does some nice work creating my new database (that should mimic the old one).
I'm using a combination of data annotations and the fluent API to describe my tables.

My database has a few indexes and I would like Entity Framework to create them as well. It seems the old way to do this is to define your own Initializer and use custom T-SQL.

But now that we have EF Migrations it should be easier to do so.
I can't seem to figure out how to combine CreateDatabaseIfNotExists<> with an automatic migration to create the indexes. I've tried to use the MigrateDatabaseToLatestVersion<,> but it doesn't seem to perform the migration after the Database has been created.

What is the proper way to create indexes and constraints on database creation now that we have Entity Framework 4.3?

4
  • You say "after database create" and "CreateDatabaseIfNotExists" did this mean you want to do this on a existing database ? Commented Apr 21, 2012 at 8:59
  • No sorry, I mean after Entity Framework created my database. So I start with no database, then I want EF to create my basic structure and after that I want the indexes. Commented Apr 21, 2012 at 9:01
  • I am not aware that ef will create indexes for you; merely provides a way to issue commands to do so yourself. Commented Apr 21, 2012 at 9:15
  • EF Migrations has helpers like CreateIndex Commented Apr 21, 2012 at 9:22

1 Answer 1

5

Don't use CreateDatabaseIfNotExists if you want to use migrations. Use MigrateDatabaseToLatestVersion from the beginning - it will create your database as well. Put your index creation code (calls to CreateIndex) into Up method of your migration class.

If you already have existing database and you want to use migrations you must first create initial migration.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.