How to mapping enum in postgresql (db first) with ef core on .net core

3.1k views Asked by At

I'm writing a middleware that logs the exceptions I get.

I created enum values ​​on postgresql

enter image description here

and mapped this to my log table

enter image description here

My Log model is:

   public class Log
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonIgnore]
    public int Id { get; set; }
    public EventType EventType { get; set; }
    public string Description { get; set; }
    public DateTime CreatedAt { get; set; }

}

My Error middleware is:

        var log = new Log();
        log.Description = ex.Message;
        log.EventType = EventType.Exception;
        log.CreatedAt = DateTime.Now;

        Context.Add(log);
        Context.SaveChanges();

(This is coming on interfaces, but I wanted to show shortly)

My Context:

 protected override void OnModelCreating(ModelBuilder model)
    {
        model
            .HasPostgresEnum(null, "event_type", new[] { "info", "unknown", "warning", "exception" });


  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseNpgsql(Configuration.GetConnectionString("MyConnection"))
            .UseCamelCaseNamingConvention();
        NpgsqlConnection.GlobalTypeMapper.MapEnum<EventType>("enum_logs_eventType");
    }

i think i did everything right. It is DB First, so I migrated the database, but I think you did the same steps there.

when i run the service and trigger any error i get this error:

enter image description here

When I try to cast to string or run .HasConversion or something i get this error:
 

stringError

1

There are 1 answers

0
hasaneyldrm On BEST ANSWER

Posthresql enum values ​​are case sensitive. So when I deleted the enums and fixed them again (they're all lowercase), the error was resolved.