Search code examples
f#npgsql

Cannot map an F# discriminated union to an Npgsql enum


I'm attempting to map F# discriminated union to an enum that Npgsql understands. I've used this documentation as reference.

Here's a code sample below:

open Npgsql
open NpgsqlTypes

type Colors =
    | Red
    | Green
    | Blue

NpgsqlConnection.GlobalTypeMapper.MapEnum<Colors>("colors") |> ignore

Unfortunately, I get the following compilation error:

A generic construct requires that the type 'Colors' have a public default constructor

Is there any way to add a default constructor to this discriminated union?


Solution

  • I haven't used Ngpsql, so I don't know if this is the issue, but your Colors union isn't an enum as you have it written. To define an enum in F#, you have to assign an integer to each value, like this:

    type Color =
       | Red = 0
       | Green = 1
       | Blue = 2