【问题标题】:How to handle F# Option type with Entity Framework Core?如何使用 Entity Framework Core 处理 F# 选项类型?
【发布时间】:2020-08-11 16:30:49
【问题描述】:

我正在使用带有 F# 的 EF Core,并且我有一个包含选项类型的实体/模型。但是,EF Core 不适用于 F#Option<T> 类型。我可以使用 Nullable<T>,但它在 F# 中不是很惯用,我更愿意坚持使用 Option 类型。

我查看了 值转换器,但文档说 null 不能使用值转换器进行转换,此外,它不能很好地处理生成的 SQL 语句,强制客户端过滤而不是使用 SQL 子句。

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

在生成具有可选值的模型时,我有什么办法可以处理这个问题?

【问题讨论】:

    标签: f# entity-framework-core


    【解决方案1】:

    您可以使用来自EFCore.FSharpvalue converter 处理选项类型。

    虽然它似乎不适用于导航属性和外键。

    【讨论】:

    • 我查看了值转换器,但根据文档,它不允许 null 值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多