Repository navigation
Closed as not planned
Closed as not planned
Copy link
Description
Hello
I am using Npgsql with EF core.
Database was created with enum column types using "CREATE TYPE ......... "
In my c# class library, i have 2 DbContexts defined. These 2 contexts have models with a property that has to map to a postgres column with my custom defined enum types ( 2 different enum types).
I followed the instructions in the documentation to add the statement:
NpgsqlConnection.GlobalTypeMapper.MapEnum
in the static constructor of my DbContext classes.
However, when i launch my application and use any of the contexts the first time, it works.
If i try to use the other, it fails.
Is there some thing i am missing ?
First Context:
public class CommandsContext : DbContext
{
public DbSet<Command> Commands { get; set; }
static CommandsContext()
{
NpgsqlConnection.GlobalTypeMapper.MapEnum<CommandType>("omms_commands");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Database=omms_test");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Command>().ToTable("devcommands").HasKey(c => c.Id);
builder.Entity<Command>().Property(c => c.Id).ValueGeneratedOnAdd().HasColumnName("id").HasColumnType("BIGSERIAL");
builder.Entity<Command>().Property(e => e.DeviceId).HasColumnName("deviceid").HasColumnType("integer");
builder.Entity<Command>().Property(e => e.Created).HasColumnName("created").HasColumnType("timestamp");
builder.Entity<Command>().Property(e => e.Sent).HasColumnName("timesent").HasColumnType("timestamp");
builder.Entity<Command>().Property(e => e.type).HasColumnName("commandtype").HasColumnType("omms_commands");
builder.Entity<Command>().Property(e => e.IsActive).HasColumnName("isactive").HasColumnType("boolean");
builder.HasPostgresEnum("omms_commands", new[] { "lock", "Unlocked" });
}
}
Second Context
public class EventsContext : DbContext
{
public DbSet<Event> Events { get; set; }
static EventsContext()
{
//NpgsqlConnection.GlobalTypeMapper.MapEnum<EventType>("omms_events");
NpgsqlConnection.GlobalTypeMapper.MapEnum<EventType>("omms_events");
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Database=omms_test");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Event>().ToTable("devevents").HasKey(ev => new {ev.DeviceId, ev.Timestamp});
builder.Entity<Event>().Property(e => e.DeviceId).HasColumnName("id").HasColumnType("integer");
builder.Entity<Event>().Property(e => e.Timestamp).HasColumnName("eventtime").HasColumnType("timestamp");
builder.Entity<Event>().Property(e => e.EventType).HasColumnName("eventtype").HasColumnType("omms_events");
builder.HasPostgresEnum("omms_events", new[] { "door_opened", "door_closed", "device_start", "device_stop", "lock_engaged", "lock_disengaged" });
}
}
This is the Error is get from the failures:
System.InvalidCastException: Can't cast database type public.omms_events to Byte
at Npgsql.Internal.TypeHandling.NpgsqlTypeHandler.ReadCustom[TAny](NpgsqlReadBuffer buf, Int32 len, Boolean async, FieldDescription fieldDescription)
at Npgsql.NpgsqlDataReader.GetFieldValue[T](Int32 ordinal)
at Npgsql.NpgsqlDataReader.GetByte(Int32 ordinal)
at lambda_method58(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator )
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
Metadata
Metadata
Assignees
Labels
No labels
Activity
roji commentedon Feb 8, 2022
Please submit a runnable code sample that shows this happening; I tried to reproduce with the code sample below, but it runs fine (you can also tweak that code sample to make it fail).
Details
AccraNET commentedon Feb 9, 2022
Hello @roji
Thanks for your reply.
After some tinkering around, i finally got it working.
what i did was to place multiple calls to
NpgsqlConnection.GlobalTypeMapper.MapEnumin each DbContext static constructor.
From my experiments, it seems the only one static constructor of the 2 DbContexts are called. The first of them to be used has its static constructor called.
Seems, NET 6 is treating them as being the same object type hence calling only on constructor.
Below is updated static constructors of both classes.
Hope it helps others.
Also will be happy if it can be pointed out why it is behaving this way
Thanks
AccraNET commentedon Feb 9, 2022
As an add on, i picked up some pointers from this article
https://sitharus.com/2018/09/npgsql-multiple-entity-framework-contexts-and-enum-mappings.html
roji commentedon Feb 9, 2022
@AccraNET
That doesn't sound right...
Any chance you could tweak my minimal code sample above to show the problem occuring? If there's a problem here, I'd like to investigate it.
dziedrius commentedon May 11, 2022
I'm having same/similar problem, created small app to reproduce: https://github.com/dziedrius/multiple-db-contexts-problem
Basically app has two DbContexts, TestContext and TestContext2.
TestContext has Client entity, which uses enum column, TestContext2 does not use any enums.
TestContext registers enum using static constructor.
If I first create TestContext, then TestContext2, everything works fine.
If I first create TestContext2, then TestContext, TestContext can not write/read enum columns anymore, it fails with:
Mentioned above article's workaround worked for me (probably because the order somehow changed), just before googling the problem I've spent quite a bit of time trying to understand what went wrong after introducing second context :)
On the side note - I usually use snake_case database naming, but for reproducing this issue I did not, so I was expecting ClientType enum type created in postgres use same naming as in code (as I needed to describe it manually in migration) - but it was using snake_case ¯_(ツ)_/¯
roji commentedon May 24, 2022
@dziedrius looking at your repro, the problem is the same as in the others above - placing MapEnum in multiple DbContext static constructors means that Npgsql will initialize for the first DbContext in use, before the 2nd MapEnum is called. All global type mappings must be done at program start, before any database code is invoked.
I'm going to go ahead and close this since I don't currently have any actual code sample which reproduces a problem; if anyone is convinced there's still a problem, please open a new issue with a runnable, minimal code sample.
dziedrius commentedon May 24, 2022
Would it make sense to explain this situation explicitly in documentation?
For example here: https://www.npgsql.org/efcore/mapping/enum.html?tabs=tabid-1
And at least in our case some kind of early exception with explanation what is going on would have helped, as you're not expecting that adding second DbContext implementation will somehow affect first one - may be some flag could be set indicating, that enum registration is too late and during subsequent registration that flag could be used to determine if exception is needed.
In my example TestContext2 does not have any enums at all (as it was in real case) - so it was even more counter intuitive to see that second context impacts enum registration for the first one.
Add note on mapping enums with multiple context types
roji commentedon May 24, 2022
@dziedrius good point - people have clearly been running into this. Pushed npgsql/doc@687dc78.
Add note on mapping enums with multiple context types