Skorunka František
Skorunka František

Reputation: 5430

Entity Framework 7 - Migrations : how to specify database provider and connection string just for migrations

Is there a way how to specify which DataProvider(SQL Server) and ConnectionString to use just for generating a migrations(Add-Migration) and updating a database(Update-Database)? I do not want to hardcode the data provider selection and connection string loading into DbContext (.UseSqlServer()).

I think EF6 can pick a connection string directly from web.config, is there something similar in EF7?

Upvotes: 2

Views: 1406

Answers (1)

Bassam Alugili
Bassam Alugili

Reputation: 16993

No you have to use optionsBuilder:

example:

string oldConnectionString =@"Server = .\;Initial Catalog=EFTutorial; AttachDbFilename=|DataDirectory|\EFTutorial.mdf; Trusted_Connection = True; MultipleActiveResultSets = true";

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer(oldConnectionString );
    base.OnConfiguring(optionsBuilder);
}

you can also load as json and load it directly from app.config or web.config.

If you are using .Net Core:

you can define in your appsettings.json the conenction string as following:

{
  {
     ....

  },
  "Data": {
           "ConnectionString": "..."   
  }
}

on App starting you have to load it:

// Set up configuration sources.
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
builder.AddEnvironmentVariables();
Configuration = builder.Build().ReloadOnChanged("appsettings.json");

After that you also have to configure Entity Framework in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
  ...
  services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<AppContext>(options =>
 { 
                     options.UseSqlServer(Configuration "Data:ConnectionString"]); });
        services.AddScoped<AppContext, AppContext>();

        ...
  }
}

The improtant thing here:

services.AddScoped((_) => new AppContext(Configuration["Data:DefaultConnection:ConnectionString"]));

https://docs.asp.net/en/latest/data/entity-framework-6.html

Examples to conenction string in Entity Framework Core 1.0 / 7: https://docs.asp.net/en/latest/fundamentals/configuration.html

The old way(You can do that also with EF Core) we have load the conenctionString from App.config or web.config and by the Migration process Add-Migration/Update-Database, EF will automatically found the Connection string. But you can also provide the conenction string to Add-Migration in the NuGet comamnd line as parameter.

I hope this will solve your Problem!

Upvotes: 1

Related Questions