Search code examples
entity-frameworkasp.net-coreconnection-string

.net core not connecting to the changed database in appsettings.json connectionstrings in visual studio debug


I am working on a .net core project, I wanted to change the connectionstring of the database in appsettings.json. I had created a duplicate database and named it originalname_fake01 and made a clone of the original database for testing.

I have also changed the database name in appsettings.developement.json. Everything seems fine but when I run the application in debug mode in visual studio. the data was being pulled from the original database rather than the changed database name in appsettings.json.

Here is my appsettings connectionstrings code: Old connectionstring was

"connectionStrings": {
"MyConnectionString": 
"Server=localhost;port=3306;database=mydb;user=root;password=rt123;"
}

changed connection string (new)

"connectionStrings": {
"FakeConnectionString": 
"Server=localhost;port=3306;database=mydb_fake01;user=root;password=rt123;"
}

I am not able to understand why it is connecting to the old database rather than the new database even after changing the connectionstring.

Any help would be appreciated.


Solution

  • I have finally able to find the problem in the dbcontext.cs modelbuilder. There is a code line which has strongly typed Schema Name.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
          {
             base.OnModelCreating(modelBuilder);
             OnModelCreatingImpl(modelBuilder);
    
             modelBuilder.HasDefaultSchema("MyDB");
    }
    
    

    I changed it use the new schema as below:

    modelBuilder.HasDefaultSchema("MyDB_Fake01");
    

    I don't understand why we need to give schema name in both connectionstring and in modelbuilder. I Guess we should avoid explicit schema name targeting in ModelBuilder so that, whenever the connectionstring is changed. it will target the database correctly.

    Anyways, the problem is solved as the application is connecting to the intended database.