Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This has proved to be a popular post so I have updated it in light of feedback from others. The main thing to know is that the Seed method in the Configuration class is run EVERY time the application starts, which isn't what the comment in the template method implies. See the answer from someone at Microsoft to this <a href="https://stackoverflow.com/questions/10822618/confusion-over-ef-auto-migrations-and-seeding-seeding-every-program-start">post</a> about why that is - thanks to Jason Learmouth for finding that.</p> <p>If you, like me, only want to run the database updates if there are any pending migrations then you need to do a bit more work. You can find that out if there are pending migrations by calling migrator.GetPendingMigrations(), but you have to do that in the ctor as the list of pending migrations is cleared before Seed method is called. The code to implement this, which goes in the Migrations.Configuration class is as follows:</p> <pre><code>internal sealed class Configuration : DbMigrationsConfiguration&lt;YourDbContext&gt; { private readonly bool _pendingMigrations; public Configuration() { // If you want automatic migrations the uncomment the line below. //AutomaticMigrationsEnabled = true; var migrator = new DbMigrator(this); _pendingMigrations = migrator.GetPendingMigrations().Any(); } protected override void Seed(MyDbContext context) { //Microsoft comment says "This method will be called after migrating to the latest version." //However my testing shows that it is called every time the software starts //Exit if there aren't any pending migrations if (!_pendingMigrations) return; //else run your code to seed the database, e.g. context.Foos.AddOrUpdate( new Foo { bar = true}); } } </code></pre> <p>I should point out that some people have suggested putting the seed code in the actual 'up' migration code. This works, but means you need to remember to put the seed code in each new migration and its pretty hard remember so I wouldn't do that. However if your seed changes with each migration then that might be the a good way to go.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload