Entity Framework connecting to different database instance despite correct connection string configuration

I’m dealing with a confusing situation where Entity Framework seems to ignore my connection string settings.

My setup:

  • One SQL Server machine running two instances: localhost\development and localhost\production
  • One IIS server hosting two applications: dev-app and prod-app

The dev-app has its web.config configured to connect to localhost\development, while prod-app connects to localhost\production. Both database instances are set up identically with same database names, credentials, and schemas. They only differ in the ports they use.

I have this code running in my dev-app:

_log.Info("Current connection: " + _dbContext.Database.Connection.ConnectionString);

_dbContext.Database.ExecuteSqlCommand("my_stored_proc @parameter");

The weird thing is that when I check my logs, the connection string clearly shows it’s pointing to the localhost\development instance like it should. However, when I run SQL Server Profiler, I can see that my_stored_proc is actually being executed on the localhost\production instance instead.

This makes no sense to me. The connection string looks correct in the logs, but the actual database calls are going somewhere else. Has anyone seen this behavior before? What could cause Entity Framework to connect to a different instance than what’s specified in the connection string?

I encountered something similar when working with multiple named instances. The issue turned out to be related to SQL Server Browser service configuration. When SQL Server Browser isn’t properly routing requests to the correct named instance, connections can end up hitting the default instance or get redirected unexpectedly. Check if your SQL Server Browser service is running and properly configured on the database server. Also verify that both instances are actually listening on different ports by checking SQL Server Configuration Manager. Sometimes what appears to be two separate instances might actually be aliases pointing to the same underlying instance, especially if they were set up through configuration tools rather than separate installations.

hmm this is really strange behavior! are you absolutley sure both apps aren’t sharing the same app pool in iis? that could explain why the connection is getting mixed up. also curious - when you say the ports are different, are you specifying the port numbers explicitly in your connection strings? would love to see the actual connection string if you can share it (minus sensitive info obviously)

thats really bizzare… have you checked if theres any connection pooling issues? sometimes ef can reuse connections from the pool that were created with different connection strings. try adding Pooling=false to your connection string temporarly to see if that fixes it