Skip to content

Can we share connection between DbContexts using shared NpgsqlDataSource? #3053

Closed as duplicate

Description

@uhfath

I'm trying to share transactions between contexts using UseTransaction method.
The idea was to use shared NpgsqlDataSource to share connection between contexts.
Currently this is implemented like this:

var builder = new NpgsqlDataSourceBuilder(connectionString);
sharedDataSource = builder.Build(); //actually stored in a singleton class
...
services.AddDbContext<MedServiceDbContext>((sp, opts) => opts.UseNpgsql<MedServiceDbContext>(sharedDataSource));

And used like this:

using var scope_1 = _serviceScopeFactory.CreateScope();
using var transaction_1 = scope_1.ServiceProvider.GetRequiredService<MedServiceDbContext>().Database.BeginTransaction();
var dbContext_1 = scope_1.ServiceProvider.GetRequiredService<MedServiceDbContext>();
dbContext_1.Units.Add(new Unit { Code = "1", IsEnabled = true, Title = "test", });
dbContext_1.SaveChanges();

using var scope_2 = _serviceScopeFactory.CreateScope();
var dbContext_2 = scope_2.ServiceProvider.GetRequiredService<MedServiceDbContext>();
dbContext_2.Database.UseTransaction(transaction_1.GetDbTransaction()); //exception here
var tmp_2 = dbContext_2.Units.ToArray();

Unfortunately we get an exception of:

The specified transaction is not associated with the current connection. Only transactions associated with the current connection may be used.

Can we share connection using NpgsqlDataSource or something else has to be done for that?

Activity

  1. uhfath commented on Jan 10, 2024

    @uhfath
    Author

    Looks like we need to share not the NpgsqlDataSource, but NpgsqlDataSource.CreateConnection(). In this case connection sharing works as expected.
    Am I right in assumption that sharing NpgsqlDataSource is useful not for connections but for mappings?

  2. uhfath commented on Jan 13, 2024

    @uhfath
    Author

    Going further, it seems that sharing NpgsqlConnection using NpgsqlDataSource.CreateConnection doesn't actually share mappings which were made using the NpgsqlDataSource.
    How do we share both? Connection and the mappings from NpgsqlDataSource.

    I'll elaborate a bit.
    When using shared NpgsqlDataSource my queries which use mapped enums work fine.
    However, when trying to share connection using the very same shared NpgsqlDataSource (which is registered as singleton) through a call to NpgsqlDataSource.CreateConnection() I get an exception for queries which use mapped enums which looks like this:

    Npgsql.PostgresException (0x80004005): 42883: operator does not exist: report_period_state_type = integer
    
    POSITION: 103
       at Npgsql.Internal.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|234_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlDataReader.NextResult()
       at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior)
       at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
       at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
       at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
       at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
       at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
       at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
      Exception data:
        Severity: ERROR
        SqlState: 42883
        MessageText: operator does not exist: report_period_state_type = integer
        Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
        Position: 103
        File: parse_oper.c
        Line: 656
        Routine: op_error
    

    Here report_period_state_type is my enum which is mapped during NpgsqlDataSource building like this:

    var builder = new NpgsqlDataSourceBuilder(connectionString);
    builder.MapEnum<...>(...);
    DataSource = builder.Build();
  3. roji commented on Jan 13, 2024

    @roji
    Member

    @uhfath it will take me a while before I'll have time to investigate this - but make sure that the connection you pass in came from the exact same NpgsqlDataSource that you passed to UseNpgsql() when configuring EF.

  4. uhfath commented on Jan 13, 2024

    @uhfath
    Author

    Actually currently what I do is:

    1. Create a singleton service with NpgsqlDataSource which has all the mappings applied;
    2. Use UseNpgsql with NpgsqlDataSource.CreateConnection() from that singleton.

    So I'm not using the NpgsqlDataSource in UseNpgsql now, but a direct connection from it which gives the aforementioned exception. In this case the connection is shared, but not the mappings.
    When using NpgsqlDataSource with UseNpgsql the mappings work, but connection is not shared.

  5. roji commented on Jan 13, 2024

    @roji
    Member

    That's probably the expected behavior - EF pulls its enum mappings from the data source you configure it with - or from the global type mapper (so you should be able to do NpgsqlConnection.GlobalTypeMapper.MapEnum() before doing anything, and it should work).

    But none of this should be needed - it should work just fine to share a connection for the transaction, as long as everything comes from the same data source. I'll try to take a look in the coming days.

  6. uhfath commented on Jan 13, 2024

    @uhfath
    Author

    I'll explain my case in more details.
    We have a "main" DbContext, which holds the app's main data. There are other contexts for auxiliary data as well as a large object manager. They are all used within the same db transaction and connect to the same database when processing a single request: create some data in multiple contexts and some "files" along with them. The latter uses NpgsqlConnection directly.

  7. NinoFloris commented on Jan 13, 2024

    @NinoFloris
    Member

    It's fairly simple, if you expect to use an enum type in some dbcontext then either:

    • The datasource used in that dbcontext configuration has to have the enum registered.
    • If you configure the dbcontext with a connection instead of a datasource you have to set up the enum on the global mapper instead.

    Whether you give that dbcontext some other connection later on or not doesn't matter (i.e. there is no dynamic loading happening, only during configure).

  8. uhfath commented on Jan 14, 2024

    @uhfath
    Author

    @roji, @NinoFloris I tried to avoid using GlobalTypeMapper since it's going to be deprecated and also trying to avoid any other such global stuff.
    As to mappings and connections, my expectations were that since NpgsqlDataSource.CreateConnection() is called from an already configured datasource it should contain all the mappings made to it.

  9. roji commented on Jan 14, 2024

    @roji
    Member

    @uhfath can you please submit a minimal, runnable console program so that we can see exactly what you're trying to do? That's always a good idea when reporting a problem.

  10. uhfath commented on Jan 14, 2024

    @uhfath
    Author

    @roji sure, here it is: https://github.com/uhfath/TestDbContextSharing
    This is a simplified version of our project.
    Different type of "sharing" is picked by commenting and uncommenting lines from 20 to 26.

    The strange thing I've noticed is that when using data source sharing the SQL query (from line 42) generated looks like this:

    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (9ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT c."Id", c."ClientType", c."Name"
          FROM "Clients" AS c
          WHERE c."ClientType" <> 'old'::client_type
    

    But when using connection sharing it looks like this:

    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT c."Id", c."ClientType", c."Name"
          FROM "Clients" AS c
          WHERE c."ClientType" <> 1
    

    Note the last line in each query where condition is.
    Somehow in our main app this gives an aforementioned exception of "operator does not exist" but in this sample it works fine. Not sure why, but still it looks different.
    Is this because we are not using GlobalTypeMapper but configure mappings locally for NpgsqlDataSource?

    Also when using data source sharing the sample gives an InvalidOperationException because the context created doesn't see the changes made from another context.
    But it works when sharing connection (except that mapping issues mentioned before).

    The idea was to use a scoped service which holds a connection for selected contexts and could be also used for other operations (large objects mainly).

  11. roji commented on Jan 15, 2024

    @roji
    Member

    Somehow in our main app this gives an aforementioned exception of "operator does not exist" but in this sample it works fine. Not sure why, but still it looks different.

    I'm not really going to be able to help there - you'll have to figure out the difference between your sample and your application...

    Is this because we are not using GlobalTypeMapper but configure mappings locally for NpgsqlDataSource?

    As @NinoFloris and I wrote above, this depends on where the connections are coming from; if they're coming from a data source, they should have the DS's config (with the enum mapping). If not, they won't, and will only have mappings configured on GlobalTypeMapper (but that's not a great way to do things).

    So to summarize, I've looked at your sample, and I'm seeing multiple EF DbContext types (MainDbContext, ReadOnlyMainDbContext...) configured with a single NpgsqlDataSource - that's looks good. The code seems to work fine - your query on line 42 uses the enum mapping (as you've noted). I can see a transaction getting created, but not shared, which is what you opened this issue about originally.

    So basically we need an actual code sample that shows a problem...

  12. uhfath commented on Jan 16, 2024

    @uhfath
    Author

    @roji sorry for the confusion. Must be because of my experiments while trying to figure it out.

    Actually the project I've shared is an actual code with the problem.
    I'll try to explain more.

    When lines 20-22 are uncommented the sample works by using a singleton NpgsqlDataSource:
    image

    In this case connection is not shared between contexts as well as transactions (they are not shown here, but it's irrelevant in this case). And when ran the sample gives InvalidOperationException as defined on line 48 since ReadOnlyMainDbContext doesn't see changes made in MainDbContext. That's logical I guess. And the SQL generated from a query on line 42 looks like this:

    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT c."Id", c."ClientType", c."Name"
          FROM "Clients" AS c
          WHERE c."ClientType" <> 'old'::client_type // <-- **note this line**
    

    The mappings defined in a NpgsqlDataSource are used correctly.

    When lines 24-26 are uncommented the sample works by sharing a connection from the very same singleton NpgsqlDataSource through NpgsqlDataSource.CreateConnection():
    image

    In this case connection is shared correctly. Since it is built from a single NpgsqlDataSource transaction also can be shared. But the SQL generated from a query on line 42 now looks like this:

    info: Microsoft.EntityFrameworkCore.Database.Command[20101]
          Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT c."Id", c."ClientType", c."Name"
          FROM "Clients" AS c
          WHERE c."ClientType" <> 1 // <-- **note this line**
    

    So it seems that even though connection is created from the pre-configured and pre-mapped NpgsqlDataSource it doesn't seem to actually use the mappings defined in it.

    P.S. This was tested using Npgsql.EntityFrameworkCore.PostgreSQL version 7.0.11 using .NET 7

    Hope this explains my case more.
    If there are more questions left I'll try my best to explain or produce another sample.

  13. roji commented on Jan 16, 2024

    @roji
    Member

    OK, thanks for providing more details - I see now.

    That makes sense; the issue is that while the NpgsqlConnections indeed come from the same NpgsqlDataSource and therefore share the enum mapping at the lower-level ADO.NET, the enum mappings aren't configured at the EFCore.PG level; this is because EFCore.PG's NpgsqlTypeMappingSource gets its enum type mappings either from the configured NpgsqlDataSource (the one passed to UseNpgsql()) or from the global type mapper. It's not possible for get the enum type mappings from an NpgsqlConnection, since NpgsqlTypeMappingSource is an EF singleton service, but NpgsqlConnection is potentially different for each connection.

    The unfortunate workaround is to perform the enum mappings on the global type mapper for now; these will automatically propagate everywhere and make this work. Although the global type mapper is obsolete, we're unlikely to actually remove it any time soon, so it should be fine to use this as your workaround until this is properly resolved.

    The right fix here is to for EFCore.PG to stop pulling enum type mappings out of NpgsqlDataSource; this is something I've been wanting to do for a while (for other reason as well) - #3063 tracks that.

    I'll go ahead and close this now, as the situation seems clear and there's a workaround - but don't hesitate to post back if you have other questions/insights.

  14. roji commented on Jan 16, 2024

    @roji
    Member

    Duplicate of #3063

  15. uhfath commented on Jan 16, 2024

    @uhfath
    Author

    @roji thanks for taking the time to look into this.
    We indeed currently use a mentioned workaround with global mapping but will be waiting for changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions