You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Can we share connection between DbContexts using shared NpgsqlDataSource? #3053
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:
varbuilder=newNpgsqlDataSourceBuilder(connectionString);sharedDataSource=builder.Build();//actually stored in a singleton class...services.AddDbContext<MedServiceDbContext>((sp,opts)=>opts.UseNpgsql<MedServiceDbContext>(sharedDataSource));
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?
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:
@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.
Create a singleton service with NpgsqlDataSource which has all the mappings applied;
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.
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.
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.
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).
@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.
@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.
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).
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...
@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:
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():
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.
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.
@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.
Activity
uhfath commentedon Jan 10, 2024
Looks like we need to share not the
NpgsqlDataSource, butNpgsqlDataSource.CreateConnection(). In this case connection sharing works as expected.Am I right in assumption that sharing
NpgsqlDataSourceis useful not for connections but for mappings?uhfath commentedon Jan 13, 2024
Going further, it seems that sharing
NpgsqlConnectionusingNpgsqlDataSource.CreateConnectiondoesn't actually share mappings which were made using theNpgsqlDataSource.How do we share both? Connection and the mappings from
NpgsqlDataSource.I'll elaborate a bit.
When using shared
NpgsqlDataSourcemy 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 toNpgsqlDataSource.CreateConnection()I get an exception for queries which use mapped enums which looks like this:Here
report_period_state_typeis my enum which is mapped duringNpgsqlDataSourcebuilding like this:roji commentedon Jan 13, 2024
@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.
uhfath commentedon Jan 13, 2024
Actually currently what I do is:
NpgsqlDataSourcewhich has all the mappings applied;UseNpgsqlwithNpgsqlDataSource.CreateConnection()from that singleton.So I'm not using the
NpgsqlDataSourceinUseNpgsqlnow, but a direct connection from it which gives the aforementioned exception. In this case the connection is shared, but not the mappings.When using
NpgsqlDataSourcewithUseNpgsqlthe mappings work, but connection is not shared.roji commentedon Jan 13, 2024
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.
uhfath commentedon Jan 13, 2024
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
NpgsqlConnectiondirectly.NinoFloris commentedon Jan 13, 2024
It's fairly simple, if you expect to use an enum type in some dbcontext then either:
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).
uhfath commentedon Jan 14, 2024
@roji, @NinoFloris I tried to avoid using
GlobalTypeMappersince 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.roji commentedon Jan 14, 2024
@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.
uhfath commentedon Jan 14, 2024
@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:
But when using connection sharing it looks like this:
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
GlobalTypeMapperbut configure mappings locally forNpgsqlDataSource?Also when using data source sharing the sample gives an
InvalidOperationExceptionbecause 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).
roji commentedon Jan 15, 2024
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...
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...
uhfath commentedon Jan 16, 2024
@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: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
InvalidOperationExceptionas defined on line 48 sinceReadOnlyMainDbContextdoesn't see changes made inMainDbContext. That's logical I guess. And the SQL generated from a query on line 42 looks like this:The mappings defined in a
NpgsqlDataSourceare used correctly.When lines 24-26 are uncommented the sample works by sharing a connection from the very same singleton

NpgsqlDataSourcethroughNpgsqlDataSource.CreateConnection():In this case connection is shared correctly. Since it is built from a single
NpgsqlDataSourcetransaction also can be shared. But the SQL generated from a query on line 42 now looks like this:So it seems that even though connection is created from the pre-configured and pre-mapped
NpgsqlDataSourceit doesn't seem to actually use the mappings defined in it.P.S. This was tested using
Npgsql.EntityFrameworkCore.PostgreSQLversion7.0.11using.NET 7Hope this explains my case more.
If there are more questions left I'll try my best to explain or produce another sample.
roji commentedon Jan 16, 2024
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.
roji commentedon Jan 16, 2024
Duplicate of #3063
uhfath commentedon Jan 16, 2024
@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.