How to handle F# Option type with Entity Framework Core?

Viewed 567

I am using EF Core with F# and I have a entity/model that contains option type. However, EF Core doesn't work well with F# Option<T> type. I could use Nullable<T> but it is not very idiomatic in F# and would prefer to stick with Option type.

I looked into Value Converter but documentation says that null cannot be converted using value converter and additionally, it doesn't play well with generated SQL statements, forcing the client-side filtering instead of using SQL clauses.

namespace Db

open Microsoft.EntityFrameworkCore

open System

[<CLIMutable>]
type Invitation =
    { Id: Guid
      Code: string

      // HOW TO HANDLE OPTION TYPE
      FirstName: string option
      LastName: string option
      Email: string
      GeneratedAt: DateTime }

[<CLIMutable>]
type User =
    { Id: Guid
      FirstName: string
      LastName: string
      Email: string
      Password: string
      PasswordSalt: string
      PasswordHash: string }


type AppContext(opts) =
    inherit DbContext(opts)

    [<DefaultValue>]
    val mutable private invitation: DbSet<Invitation>

    member x.Invitation
        with get() = x.invitation
        and set v = x.invitation <- v


    [<DefaultValue>]
    val mutable private user: DbSet<User>

    member x.User
        with get() = x.user
        and set v = x.user <- v


    override _.OnConfiguring (options: DbContextOptionsBuilder) =
        options.UseSnakeCaseNamingConvention()
        |> ignore

Is there any way I can handle this while generating the model with optional value?

1 Answers

You could handle option types using this value converter from EFCore.FSharp.

Although it doesn't seem to work with navigation properties and foreign keys.

Related