Have a better story for EFCore.PG and multihost

Abierto
#3,495 9 comentarios 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 1 día

@roji ya está trabajando en esto.

Desde el 10/3/2025.

Evaluación

Este issue todavía no se ha evaluado.

Descripción

Try to have Target Session Attributes in the connection string fails the moment EFCore.PG needs to create a data source internally (full repro below):

.UseNpgsql(
	"Host=x,y;Database=test;Username=test;Password=test;Load Balance Hosts=true;Target Session Attributes=prefer-standby",
	config =>
	{
		config.ConfigureDataSource(o => {});
	})

This throws "When creating a multi-host data source, TargetSessionAttributes cannot be specified".

The Npgsql story for target sessions is to call BuildMultiHost() instead of Build(), and then to call an overload of OpenConnectionAsync() that passes TargetSessionAttributes, or to extract wrapper data sources via WithTargetSession() (docs).

EFCore.PG doesn't know whether the connection string contains multiple hosts and/or Target Session Attribute, and never calls BuildMultiHost(). It seems like the thing to do would be to add an EF-level context option for the target session, and when EF creates the NpgsqlConnection, to call OpenConnectionAsync(TargetSessionAttributes).

Note that we also have legacy mode (without NpgsqlDataSource), where we do allow Target Session Attribute in the connection string; we internally create a wrapper for the given target session and use that. We could do the same when NpgsqlDataSourceBuilder.Build() is called with a Target Session Attribute; but that would mean that the underlying NpgsqlMultiHostDataSource (which owns the actual connection pools) isn't accessible, and it's impossible to have multiple Target Session Attribute values referencing the same physical connections. In legacy mode the NpgsqlMultiHostDataSource is global, so this isn't a problem.

In the meantime, the workaround is simply to construct a multi-host data source outside EF, get a wrapper via WithTargetSession() and pass that to EFCore.PG's UseNpgsql().

@NinoFloris @vonzshik does this all make sense?

Originally raised by @fmendez89 in https://github.com/npgsql/doc/issues/263#issuecomment-2708845653

Full repro
await using var context = new BlogContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(
                "Host=localhost,localhost:6432;Database=test;Username=test;Password=test;Load Balance Hosts=true;Target Session Attributes=prefer-standby",
                config =>
                {
                    // The moment we call ConfigureDataSource(), EF attempts to build a data source internally (with NpgsqlDataSourceBuilder.Build()),
                    // causing an exception because Target Session Attributes is present in the connection string. 
                    config.ConfigureDataSource(o => {});
                })
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Lenguaje dominante
C#
Estrellas
1.8k
Forks
268
Merge medio
2 h 35 min
PR fusionados (30 d)
136

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de npgsql/efcore.pg

Todos los issues de npgsql/efcore.pg

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.