none
Automatic Migrations Seed only on Create Database RRS feed

  • Question

  • Hi
    I'm using EF code first with automatic migrations (MigrateDatabaseToLatestVersion).
    So, I don't have access to the methods of up () and down () of the migration process, I only have available the seed method for write operations indepotentes.
    But I need to run an operation in the seed method that executes only if the migration process created the database, I need some seeding operations are performed only once and never again.
    In summary, I need to use the () database exists in the body of the seed () method, but for obvious reasons, the migration process only calls the seed () after the database is created, and the return of the method exists () is always true.
    Any tips?
    Victor Perez
    Thursday, June 29, 2017 6:09 PM

Answers

  • Hi VictorPerez,

    Base on your description,I suggest you use a flag variable to ensure the code running only once. If the database does not exist in the past but now exists.

    The following code for your reference.

    Database.SetInitializer(new MigrateDatabaseToLatestVersion<Student6Context, Configuration>());
    using (Student6Context db = new Student6Context())
    {
         //Check if tha database has existed.
    
        flag = db.Database.Exists();                      
    }
    

    the Configuration code:

    protected override void Seed(EF_CodeFirst.Student6Context context)
    {
    
    //If the database does not exist in the past but now exists.it has met your requirement.
    
      if (!Program.flag) {
          //seed data
    
      }
    
    }
    

    If you have any issues,please feel free to contact me.

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by VictorPerez Thursday, July 6, 2017 1:46 PM
    Friday, June 30, 2017 10:30 AM
    Moderator