Skip to content

Add .NET docs to Postrgres connection examples #2070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions postgres/connecting/app-connection-examples.html.markerb
Original file line number Diff line number Diff line change
Expand Up @@ -371,3 +371,50 @@ if (config.use_env_variable) {
}
```
</details>

## Connecting with .NET - EF Core & Npgsql
[docs](https://www.npgsql.org/efcore/index.html?tabs=onconfiguring#configuring-the-project-file)

Minimal parsing setup using the `DATABASE_URL` environment variable provisioned automatically with attaching a pg app. In ```Program.cs```:

```csharp
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
var databaseUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
if (!string.IsNullOrEmpty(databaseUrl))
{
Uri uri;

try
{
uri = new Uri(databaseUrl);
}
catch (UriFormatException ex)
{
throw new InvalidOperationException(
"The DATABASE_URL environment variable is not a valid URI.",
ex
);
}

var userInfo = uri.UserInfo.Split(':');
var dbUserFromUrl = userInfo[0];
var dbPwFromUrl = userInfo.Length > 1 ? userInfo[1] : "";
var dbHostFromUrl = uri.Host;
var dbPortFromUrl = uri.Port > 0 ? uri.Port.ToString() : "5432";
var dbNameFromUrl = uri.AbsolutePath.TrimStart('/');

// Extract sslmode if present
var sslMode = "Require";
var query = HttpUtility.ParseQueryString(uri.Query);
if (!string.IsNullOrEmpty(query["sslmode"]))
{
sslMode = query["sslmode"];
}

var npgsqlConn =
$"Host={dbHostFromUrl};Port={dbPortFromUrl};Database={dbNameFromUrl};Username={dbUserFromUrl};Password={dbPwFromUrl};SSL Mode={sslMode};Trust Server Certificate=true";
options.UseNpgsql(npgsqlConn);
}
});
```