简体   繁体   中英

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

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

I created enum values on postgresql

在此处输入图像描述

and mapped this to my log table

在此处输入图像描述

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:

在此处输入图像描述

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

字符串错误

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM