18

Hi I'm using the Beta 1 version of this nuGet package, the database is allready created and I need to know if there is a way to populate my tables through migrations. Thanxs

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
Guillermo Oramas R.
  • 1,303
  • 2
  • 14
  • 31

1 Answers1

18

The intro post shows how to seed data http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-no-magic-walkthrough.aspx

Seed data: Override the Seed method in this class to add seed data. - The Seed method will be called after migrating to the latest version. - You can use the DbContext.AddOrUpdate() helper extension method to avoid creating duplicate seed data. E.g.

myContext.AddOrUpdate(c => c.FullName,
  new Customer { FullName = "Andrew Peters", CustomerNumber = 123 },
);
Betty
  • 9,109
  • 2
  • 34
  • 48
  • 3
    I was implementing the answer and I noticed that indeed I can write my seeds at the Configuration file, but everytime I use the Update-Database code, those seed are going to populate the DB, everytime! :( ... I try adding the seed on the migrations files instead, but I think it doesnt work that way. Can you help me with this, i just want those seeds populate my db once and not every time i go Update-Database, thanxs pal – Guillermo Oramas R. Dec 14 '11 at 16:38
  • 2
    You have access to the context at that point, you could easily do wrap a myContext.Tablename.Any() around the code block. – Betty Dec 15 '11 at 04:04
  • 1
    I actually find it's better to create a migration and use Sql("Insert blah...") instead of using AddOrUpdate. – Betty Aug 13 '12 at 01:08
  • 3
    This is a little out-of-date. That post for instance no longer exists. Good answer at http://stackoverflow.com/questions/9342459/best-way-to-incrementally-seed-data-in-entity-framework-4-3 – Ralph Lavelle Oct 21 '12 at 00:08