.net-coreentity-framework-coreef-code-firstaspnetboilerplate

How to run Update Database using Code first in Entity Framework Core?


I run the Update-Database from visual studio to create a database, it works fine. I have published the app on a production server. But I cannot run Update-Database there. So how it can be done on the server where there is no visual studio?

I thought to create it when the application starts the first time. But I didn't get any reference or sample code.

I'm using .net core 2.0.


Solution

  • First I want to warn you that I do not know what consequences the following code may have, since I do not know enough about the Abp architecture.

    In the ProjectName.Web.Mvc project, in the ConfigureServices method, add the following code:

    public IServiceProvider ConfigureServices(IServiceCollection services) {
    
        // other stuff
    
        string connectionString = _appConfiguration
                .GetConnectionString("Default");
    
        services.AddDbContext<YouDbContextTypeName>(opt => 
            opt.UseSqlServer(connectionString)
        );
    
        // other stuff
    }
    

    In the same file in the Configure method, add the following code:

    public void Configure(
        IApplicationBuilder app, 
        IHostingEnvironment env, 
        YouDbContextTypeName context) {
    
        context.Database.Migrate();
    
        // other stuff
    }