Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for empty discriminated union #147

Open
EspenBrun opened this issue Oct 9, 2022 · 2 comments
Open

Support for empty discriminated union #147

EspenBrun opened this issue Oct 9, 2022 · 2 comments

Comments

@EspenBrun
Copy link
Contributor

EspenBrun commented Oct 9, 2022

Hello,

Thanks for this awesome package!

Is your feature request related to a problem? Please describe.
I would like to use an empty discriminated union to hold in my records

type BlogType
    | Essay
    | Long

Describe the solution you'd like
Something like registerEmptyUnionCases(), so I can just use mye EquineBeast DU as normal in by fsharp code.

If a define an Enum, it will be stored as 0, 1, 2 in the database.

Describe alternatives you've considered
If I could define a value converter on the ModelSnapshot that would also solve my problem (although registering in _.OnConfigure once would be much preferred). I have tried something like this with no luck (does not compile)

            b.Property<BlogType>("BlogType")
                .HasMaxLength(16)
                .HasColumnType("char(16)")
                .HasConversion (fun v -> v.ToString(), fun v -> BlogType.fromString v)
                |> ignore
@EspenBrun
Copy link
Contributor Author

EspenBrun commented Oct 24, 2022

This works

let duValueConverter<'a> =
   ValueConverter<'a, string>((fun v -> v.ToString()), (fun v -> fromStringOrFail<'a>(v)))

and

            b.Property<BlogType>("BlogType")
                .HasConversion (duValueConverter<BlogType>)
                |> ignore

Would still be nice to just have a registerEmptyUnionCases() that handled this for every empty DU

@EspenBrun
Copy link
Contributor Author

The fromStringOrFail utility for anyone intersted:

// utility
let inline fromStringOrFail<'a> (s: string) =
    let duType = typeof<'a>

    match
        FSharpType.GetUnionCases duType
        |> Array.filter (fun case -> case.Name = s.Replace(" ", ""))
    with
    | [| case |] -> FSharpValue.MakeUnion(case, [||]) :?> 'a
    | _ -> failwith $"Could not parse {s} to {duType.Name}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant