This post was most recently updated on August 29th, 2020.
Reading Time: 2 minutes.A while ago, I had a situation where a DbContext was misbehaving after deployed to an Azure App Service, and I needed to check the connection string it’s using directly in the code. I had reason to think my code was grabbing an outdated connection string and using a wrong database – and as you can probably imagine, that could cause some issues!
However, finding the right method actually took me googling, as there were plenty of examples for Entity Framework for .NET Framework, but next to nothing for Entity Framework Core.
So – let’s fix that! Long story short, here’s how:
Solution
Time needed: 10 minutes.
How to extract the connectionstring from your Database Context in C#?
- Include the following using statements
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore; - Instantiate your DbContext (or inject it)
Whatever you do, just have it set – this is the variable we’ll be using later on as well:
// Injected in the constructor of the controller
// or instantiated in the code
ApplicationDbContext db; - Get the connection and access ConnectionString property
Like shown below:
// Fetch the DbConnection object and grab its Connection String
db.Database.GetDbConnection().ConnectionString
Oh – a quick word of advice: The connection string will contain your password. Don’t log it anywhere as is. If you plan to push it to Application Insights or something, remove the password from the string before doing that. - (Optional) Sanitize your connection string to remove the password 😅
In case you’re displaying or logging this information somewhere, you need to (at the very least) remove the password. Below, I’m displaying one possible way to do that:
Regex r = new Regex("Password='.+'");
string dummyPassword = "Password='Password123'";
string cs = db.Database.GetDbConnection().ConnectionString;
string csSanitized= r.Replace(cs, dummyPassword);
_monitor.TrackEventDebug("ReadOnlyDbContext", "ConnectionString", csSanitized);
And that should be it!
This instruction applies to .NET Core + EF Core (at least starting form around version 3.0).
- How to fix “System.IO.FileSystem: Could not find a part of the path \AppData\Local\AzureFunctionsTools\Releases\3.17.0\workers. Value cannot be null. (Parameter ‘provider’)” when running Azure Functions locally? - January 12, 2021
- How to nuke the Identity Cache in Visual Studio? - January 11, 2021
- Fixing unexpected Microsoft.AspNetCore package errors after a dependency update - January 6, 2021