Search code examples
asp.net-coreentity-framework-corepublish

On publish Entity Framework is connecting to the wrong database


I have Asp.Net Core 5.0 and Entity Framework 5.0.12. When I change the connection string I'm changing it in both appsettings.json and in ProgramContext. Then I do build and Publish in folder or Publish with FTP. Both times I make sure the publisher is using the correct connection string.

Then I deploy and I can see that on the deployed the publisher is using the old connection string. Please help how my newly published api to use the new connection string.

For those who will say put some code as example(so irrelevant) in appsettings.json I have

  "ConnectionStrings": {
    "DefaultConnection1": "Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword"

 

Then in services.cs I have

services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection1")));

in MyContext.cs I have

if (!optionsBuilder.IsConfigured)
 {
      optionsBuilder.UseSqlServer("Data Source=MyDatabaseServer;Initial Catalog=myDatabaseName;MyUser;Password=MyPassword");
 }

and again when I try to print context.Database.GetConnectionString() I'm getting

Data Source=MyOldDatabaseServer;Initial Catalog=myOldDatabaseName;MyOldUser;Password=MyPassword

Please help


Solution

  • Found solution

    There are 2 files: appsettings.json and appsettings.production.json. The Api is taking the connection string from the second file, appsettings.production.json, so the changes need to be done there manually.