Wednesday, December 27, 2017

Delete existing database and recreate it by EntityFramework code first for asp.net core project

1. Delete the existing database
option 1: From the Visual Studio's View->SQL Server Object Explorer, delete the existing database. Note, just delete the database file from disk is not enough, as the table is still kept in system table list.
option 2: from command line, run
dotnet ef database drop

2. Delete all files from asp.net project's Migrations folder

3. From command line, run the below command to add the migration cs script to the asp.net core project
dotnet ef migrations add initial

4.Create the database and table
option 1:  From the command line, run the below command to
dotnet ef database update

option 2: call Database.Migration method from cs code when starting app. This option is particular useful for Azure deployment with connection settings as command line is not a good option for Azure cloud deployment.
public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();
            
            using (var scope = host.Services.CreateScope()){
                var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                context.Database.Migrate();
            }
            host.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

No comments:

Post a Comment