diff --git a/postgres/connecting/app-connection-examples.html.markerb b/postgres/connecting/app-connection-examples.html.markerb index 2243770424..474b908604 100644 --- a/postgres/connecting/app-connection-examples.html.markerb +++ b/postgres/connecting/app-connection-examples.html.markerb @@ -371,3 +371,50 @@ if (config.use_env_variable) { } ``` + +## 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(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); + } +}); +```