简体   繁体   中英

Database SetInitializer is not found in MySql.Data.EntityFrameworkCore

I am using MySql.Data.EntityFrameworkCore provider to connect mysql. Now I want to seed data while intializing database using DropCreateDatabaseAlways , But it is not found when I tried to use it like this

Database.SetInitializer<SmContext>(new SMDbInitializer<SmContext>());

and my SMDbInitializer will look like this.

private class SMDbInitializer<T> : DropCreateDatabaseAlways<SmContext> 
{

      protected override void Seed(SmContext context) 
      {

         //Some code
         base.Seed(context);
      }
} 

You could create a DbInitializer.cs and call dbContext.Database.EnsureDeleted() ; to delete the existing database.

public static class DbInitializer
{
    public static void Initialize(MyDbContext context)
    {
        //Ensures that the database for the context does not exist. If it does not exist, no action is taken. 
        //If it does exist then the database is deleted.
        //Warning: The entire database is deleted an no effort is made to remove just the database objects that are used by the model for this context.
        context.Database.EnsureDeleted();

        //create the database
        context.Database.EnsureCreated();

        // Look for any students.
        if (context.Students.Any())
        {
            return;   // DB has been seeded
        }

        var students = new Student[]
        {
        new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
        new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
        new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
        new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},

        };
        foreach (Student s in students)
        {
            context.Students.Add(s);
        }
        context.SaveChanges();

        //Applies any pending migrations for the context to the database.Will create the database if it does not already exist.
        //Note that this API is mutually exclusive with DbContext.Database.EnsureCreated().
        //EnsureCreated does not use migrations to create the database and therefore the
        //database that is created cannot be later updated using migrations.
        context.Database.Migrate();
    }
}

In Program.cs, modify the Main method to do the following on application startup:

public static void Main(string[] args)
{
  var host = CreateWebHostBuilder(args).Build();

  using (var scope = host.Services.CreateScope())
 {
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService<SchoolContext>();
        DbInitializer.Initialize(context);
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred while seeding the database.");
    }
}

 host.Run();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM