Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I populate data in Entity Framework code first on database creation?

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?

like image 685
ajma Avatar asked Jan 04 '11 05:01

ajma


People also ask

How do you use code first when an existing database schema?

To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.

Which is better code first or database first in Entity Framework?

3)Database Version Control Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.


2 Answers

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

like image 98
Julie Lerman Avatar answered Nov 05 '22 17:11

Julie Lerman


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

like image 35
Ladislav Mrnka Avatar answered Nov 05 '22 17:11

Ladislav Mrnka