Vivek Nuna
Vivek Nuna

Reputation: 1

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.

Upvotes: 1

Views: 4198

Answers (2)

jazb
jazb

Reputation: 5801

You can run the change scripts made against your development Db in your say 'Test' Db. To generate the scripts you can run this which creates a file to run as say part of your deployment phase.

dotnet ef migrations script -i -o "C:\<your-path>\<your-filename>.sql"

The script generated is essentially a cumulation of all the 'Up' migrations. The script is 'idempotent' in that it only applies migrations if they haven't already been applied to the database.

REF: dotnet CLI

Upvotes: 1

XelaNimed
XelaNimed

Reputation: 315

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
}

Upvotes: 3

Related Questions