Home > database >  On publish Entity Framework is connecting to the wrong database
On publish Entity Framework is connecting to the wrong database

Time:02-08

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

CodePudding user response:

check you appsettings.json and appsettings.development.json

then

  1. clean Solution!
  2. delete publish folder (local)
  3. delete publish folder (server)

now publish and upload again

CodePudding user response:

It is not reading the wrong connection string. It is reading what it sees. There are a couple of reasons why this is happening. First, it is not overwritting the appsettings on the server with the new update you made on the local appsettings. in this case, simply manually update it on the server. Second, you have both appsettings.json and appsettings.development.json on the publish folder, one of them which the project reads might not be up to date. Just update it so the two appsettings have the same content. Once you figure out which of the appsettings it uses, you could just delete the unused one.

  •  Tags:  
  • Related