Repository navigation
Description
through this #568 (comment) and #648 (comment) , seems right now, the BCL date/time types are not supported when the NodaTime plugin is configured., and from this Long story short, when you set up the ADO NodaTime plugin, it "hijacks" NpgsqlDbType.Timestamp and routes it to the NodaTime type handler, instead of the built-in DateTime type handler.
// Place this at the beginning of your program to use NodaTime everywhere (recommended)
NpgsqlConnection.GlobalTypeMapper.UseNodaTime();
// Or to temporarily use NodaTime on a single connection only:
conn.TypeMapper.UseNodaTime();seems that, npgsql supports using plugins in connection level, while the extension method UseNodaTime shows :
// TODO: Global-only setup at the ADO.NET level for now, optionally allow per-connection?
NpgsqlConnection.GlobalTypeMapper.UseNodaTime();
I am wondering that if this can be implemented in per-connection way or is there any workaround here for now?
My situation here is , we have not the whole control with code we use, e.g: use aspnet.identity, hangfire.postgresql , these libs may use ef.core, may use dapper or raw npgsql. While our own dbcontext use the nodatime plugin style, if some dbcontext config using nodatime plugin, it will break all BCL ways to use datetime, even in raw npgsql.
Does the way check plugins and add corresponding type-mappers in NpgsqlRelationalConnection solve the problem ?
right now, this works for me, does this a reasonable way to fix situation here, do you have any suggestion ?
// ensure conn in di is request scoped
services.AddScoped<DbConnection>(provider =>
{
var conn = new NpgsqlConnection("conn str");
conn.Open();
// register typp mapper on connection level, not global level
conn.TypeMapper.UseNodaTime();
return conn;
})
.AddHangfire(o =>
{
// since nodatime type mapper region on connection level, it will not affect BCL datetime on hangfire use dapper with raw npgsql
o.UsePostgreSqlStorage("conn str");
})
.AddEntityFrameworkNpgsql()
.AddDbContext<XXXDbContext>((p, options) =>
{
// since conn is registered with nodatime type mapper on connection level before, ef.core will work correctly
var conn = p.GetRequiredService<DbConnection>();
options.UseNpgsql(conn,b =>
{
// DON'T USE `UseNodaTime()` extension method, since it will register nodatime on global type mapper, and it will affect BCL datetime on the application level
// UsePlugin here to register plugin on ef.core plugin model
b.UsePlugin(new NodaTimePlugin());
});
});
Activity
austindrenski commentedon Dec 11, 2018
@lust4life I'm a bit confused by the snippet you've provided.
I cleaned up the formatting to be sure, but it still looks like you register the NodaTime plugin on each connection before yielding it back and then also configure that plugin on each context.
Have I misread (or worse mis-reformatted) your snippet?
In general terms, we don't currently have much in the way of guidance for users interested in using these plugins on a per-connection basis, so it's difficult to say what the best workaround would be.
I'll take a closer look at our plugin model and see if I can put together some concrete guidance.
Related
#654
lust4life commentedon Dec 12, 2018
@austindrenski reformat the code snippet and add some comments . the idea here is to avoid register type mapper on global level.
[-]workaround in nodatime plugin live with DateTime [/-][+]Allow per-connection, non-global plugin usage[/+]roji commentedon Dec 13, 2018
There have been enough complaints about this kind of thing that we probably need to address this.
It's probably pretty easy to change from doing global type mapping at the ADO level to simply setting up the plugin on each connection. This would involve changing NpgsqlRelationalConnection to be aware of the plugins and applying them at each open.
However, we should make sure the per-connection type mapping changes don't have a prohibitive perf cost - I've opened npgsql/npgsql#2263 to optimize this.
roji commentedon Apr 17, 2019
@Jacquers this is indeed what this issue is about. I'm hoping we can get per-connection plugins working in EF Core soon. In the meantime you can check out the workaround snippet provided by @lust4life above.
roji commentedon May 3, 2019
For anyone doing this, please be aware that there's a potentially substantial performance degradation currently associated with using plugins at the connection level (rather than at the global level). npgsql/npgsql#2263 will hopefully fix this soon.
sandcastle commentedon Sep 30, 2019
@roji - are you aware of anything else that can be done at the ADO NodaTime plugin level to stop the hijacking from occurring that would enable both DateTime and NodaTime types to be used at the same time?
14 remaining items
davidroth commentedon Sep 8, 2020
Good news for everybody waiting for a solution to this issue: The npgsql noda time plugin has recently been modified to support BCL types besides nodatime types. See MR npgsql/npgsql#3124 for details. This should resolve the specific pain points described in this thread as now BCL datetime types can co-exist with Nodatime types, without any workarounds or performance issues.
Fix has been merged and is targeted for https://github.com/npgsql/npgsql/milestone/70
roji commentedon Oct 3, 2020
Moving this to backlog - it's no longer necessary since @davidroth implemented npgsql/npgsql#3124.
ProfDoof commentedon Nov 21, 2020
Ok, I may be posting this in the wrong thread but I seem to be running into problems caused by using NodaTime and Hangfire together. This appears to be related to the way that types are mapped but maybe I'm on the wrong path. If this is still related to my problem, is there a workaround? I'm on Npgsql version 5.0.0.
This is currently the way that I'm using Hangfire
and this is the way I'm turning on the NodaTime mapping
YohDeadfall commentedon Nov 21, 2020
Was fixed by npgsql/npgsql#3124 and available since Npgsql 4.1.5.
davidroth commentedon Nov 21, 2020
@fireflamemm
Yes there is a workaround 😊
Let me first explain why you are seeing the exception, although the NodaTime plugin now supports BCL types.
Dapper maps properties by using the non-generic IDataRecord indexer. You can check that if you look at dappers SqlMapper code on line 3492 and line 2962.
The NodaTime plugin overrides the default type mapping and therefore it will try to read
Instantinstead ofDateTime.If dapper would use the explicit
IDataRecord.GetDateTime(int i)method, the exception wouldn't occur because in that case, the plugin would correctly return the expected DateTime value.Fortunately, dapper supports registering custom TypeHandler instances which will solve this issue.
So to fix this issue you need to:
davidroth commentedon Nov 21, 2020
@YohDeadfall
Unfortunately not in the case of dapper. See my previous explanation. The generic apis now work all nicely and without workarounds. But as soon as a library uses the non-generic object based IDataReader methods, and implicitly assumes BCL types being returned, a workaround is necessary.
ProfDoof commentedon Nov 21, 2020
@davidroth
Thank you so much for the quick response! That seems to have cleared everything right up. Now on to the next bug! Good luck with all of this!
YohDeadfall commentedon Nov 21, 2020
@davidroth, am aware of it, but this repository for EF Core (:
artschekoff commentedon Sep 3, 2022
Thx, you saved me <3
I've only added one more type check and cast, because
LocalDateTimeis used in my models:bessgeor commentedon Aug 12, 2026
The TypeHandler workaround got broken with
Hangfire.PostgreSqlrelease 1.21: the lib migrated to Dapper.AOT which shortcuts toConvert.ToDateTime(IDataReader.GetValue(i)), thus yieldingSystem.InvalidCastException: Unable to cast object of type 'NodaTime.Instant' to type 'System.IConvertible'..As I need to share a datasource between the app own logic (which uses Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) and Hangfire (which migrated to Dapper.AOT), so I could enqueue a job in the same non-distributed transaction as I make changes in the business logic, and I don't want to migrate from NodaTime, I had to research a new workaround.
The workaround is to change what non-generic GetValue returns to something implementing IConvertible, and that is possible using Npgsql experimental API
AddTypeInfoResolverFactory.Npgsql* 10.0.3, Hangfire.PostgreSql 1.21.1
So, we need an adapter
Make a binary converter that would be able to handle (de)serialization into timestamp binary representation:
And add a factory that would register the adapter as default type for timestamp/timestamptz:
And the last part is to register the factory in the shared data source.
Keep
optionsBuilder.UseNpgsql(b => b.UseNodaTime())in your DbContext, use shared DataSource between EF and Hangfire (you probably are already doing it withHangfire.PostgreSql.IConnectionFactoryimplementation and wiring the same DataSource intoDbContextOptionsBuilder.UseNpgsql) and you are good to go until the experimental API changes. It has been experimental for almost 3Y, so it seems pretty solid now (npgsql/npgsql@e8f20a0).