Skip to content

Using multiple contexts with "NpgsqlConnection.GlobalTypeMapper.MapEnum" error #2263

Closed as not planned

Description

@AccraNET

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)

Activity

  1. roji commented on Feb 8, 2022

    @roji
    Member

    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
    Attempted repro
    await using var ctx1 = new FirstContext();
    await ctx1.Database.EnsureDeletedAsync();
    await ctx1.Database.EnsureCreatedAsync();
    
    await using var ctx2 = new SecondContext();
    await ctx2.Database.EnsureDeletedAsync();
    await ctx2.Database.EnsureCreatedAsync();
    
    ctx1.FirstEntities.Add(new() { FirstEnum = FirstEnum.B });
    await ctx1.SaveChangesAsync();
    ctx1.ChangeTracker.Clear();
    
    ctx2.SecondEntities.Add(new() { SecondEnum = SecondEnum.Y });
    await ctx2.SaveChangesAsync();
    ctx2.ChangeTracker.Clear();
    
    _ = ctx1.FirstEntities.ToList();
    _ = ctx2.SecondEntities.ToList();
    
    public class FirstContext : DbContext
    {
        public DbSet<FirstEntity> FirstEntities { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(@"Host=localhost;Username=test;Password=test;Database=test1")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasPostgresEnum<FirstEnum>();
        }
    
        static FirstContext()
        {
            NpgsqlConnection.GlobalTypeMapper.MapEnum<FirstEnum>();
        }
    }
    
    public class SecondContext : DbContext
    {
        public DbSet<SecondEntity> SecondEntities { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseNpgsql(@"Host=localhost;Username=test;Password=test;Database=test2")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasPostgresEnum<SecondEnum>();
        }
    
        static SecondContext()
        {
            NpgsqlConnection.GlobalTypeMapper.MapEnum<SecondEnum>();
        }
    }
    
    public class FirstEntity
    {
        public int Id { get; set; }
        public FirstEnum FirstEnum { get; set; }
    }
    
    public class SecondEntity
    {
        public int Id { get; set; }
        public SecondEnum SecondEnum { get; set; }
    }
    
    public enum FirstEnum { A, B, C }
    public enum SecondEnum { X, Y, Z }
  2. AccraNET commented on Feb 9, 2022

    @AccraNET
    Author

    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.MapEnum

    in 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.

    
    static CommandsContext()
            {
                NpgsqlConnection.GlobalTypeMapper.MapEnum<CommandType>("omms_commands");
                NpgsqlConnection.GlobalTypeMapper.MapEnum<EventType>("omms_events");
            }
    
     static EventsContext()
            {
                NpgsqlConnection.GlobalTypeMapper.MapEnum<CommandType>("omms_commands");
                NpgsqlConnection.GlobalTypeMapper.MapEnum<EventType>("omms_events");
            }
    

    Hope it helps others.
    Also will be happy if it can be pointed out why it is behaving this way

    Thanks

  3. roji commented on Feb 9, 2022

    @roji
    Member

    @AccraNET

    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.

    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.

  4. dziedrius commented on May 11, 2022

    @dziedrius

    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:

     ---> Npgsql.PostgresException (0x80004005): 42804: column "ClientType" is of type client_type but expression is of type integer
    

    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 ¯_(ツ)_/¯

  5. roji commented on May 24, 2022

    @roji
    Member

    @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.

  6. dziedrius commented on May 24, 2022

    @dziedrius

    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.

  7. roji commented on May 24, 2022

    @roji
    Member

    @dziedrius good point - people have clearly been running into this. Pushed npgsql/doc@687dc78.

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