Using ENUMs with Entity Framework Core Db First

125 views Asked by At

I have a PostgreSQL database in which several tables have fields which are enums. I scaffolded the Db in a MVC Application but it skipped the enum columns although there is reference to them in the DbContext.cs file like this.

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasPostgresEnum("admin", "agreement_type", new[] { "Consultancy Agreement", "Saas Contract", "Purchase Order", "Informal", "MSA" })
                .HasPostgresEnum("admin", "invoice_status", new[] { "Pending", "Overdue", "Paid", "Cancelled" })
                .HasPostgresEnum("admin", "node_type", new[] { "standard", "study" })
                .HasPostgresEnum("admin", "role_type", new[] { "Program Lead", "IT Lead", "PI Lead", "Head Office Lead", "Contracts Lead", "Finance Lead", "Supply Chain Lead" })
                .HasPostgresEnum("admin", "study_type", new[] { "hiv", "vaccine" });

The models don't have them as they were 'skipped' so how do I fix this? In the documentation it suggests adding the following to some static controller in my DbContext class:

static MyDbContext()
    => NpgsqlConnection.GlobalTypeMapper.MapEnum<Mood>();

but I don't have any such controller. In the documentation it states:

If you're creating your model from an existing database, the provider will recognize enums in your database, and scaffold the appropriate HasPostgresEnum() lines in your model. However, the scaffolding process has no knowledge of your CLR type, and will therefore skip your enum columns (warnings will be logged). You will have to create the CLR type, add the global mapping and add the properties to your entities.

but there is no explanation as to how to do this. Also there was no scaffolding of the appropriate HasPostgresEnum() lines in any of my models. So my question is, how do I create the CLR type, add the global mapping and add the properties to my entities?

0

There are 0 answers