7

I'm using code first entity framework and I would like to know how to run some code when the database is being created so that I can populate my database with some data. (note that I'm asking for on database creation, not everytime the application starts).

Does anybody know if there's a method or event I can use for this?

2 Answers 2

11

I'd like to add to Ladislav's answer. The article he pointed to shows how to create an initializer but does not show how to use an initializer to populate a newly created database. DbInitializer has a method called Seed that you can overwrite. You can see an example of how to use this in this article (or video if you prefer, which is on the same page) http://msdn.microsoft.com/en-us/data/hh272552

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

Comments

7

You can use custom database initializer - it means implementing IDatabaseInitializer and registering this initializer by calling Database.SetInitializer.

3 Comments

The article is for CTP 4, in CTP 5, they changed the initializer to DbDatabase.SetInitializer
(Ajma...we are not working with a released RTM version of Code First and Ladislav's answer is correct. It is Database.SetInitializer, not DbDatabase.)
hey that was supposed to be "now" not, "not" :)

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.