Skip to content

Instantly share code, notes, and snippets.

@baronfel
Last active July 10, 2018 02:38
Show Gist options
  • Save baronfel/b627a3087bb25045822edc9909b4aa25 to your computer and use it in GitHub Desktop.
Save baronfel/b627a3087bb25045822edc9909b4aa25 to your computer and use it in GitHub Desktop.
Marten DU support using hierarchical schema support

run dotnet run with a local database 'foo' created + plv8 installed.

module dutest
open Marten
open Npgsql
open System
open System.Reflection
open Marten
type Case1 = { id: Guid; thing: int; status: bool }
type Case2 = { id: Guid; butts: string; ``where``: DateTime }
type DU =
| Case1 of Case1
| Case2 of Case2
with member x.Id =
match x with
| Case1 c -> c.id
| Case2 c -> c.id
let connstring = "Host=localhost;Database=foo;UserName=postgres;Password=postgres"
let case1Guid = Guid.Parse "378dfc1f-98a7-4de3-a022-a4835ce9fbe7"
let case2Guid = Guid.Parse "716e9e89-cae3-4603-ac0e-080c90136737"
[<EntryPoint>]
let main _argv =
let store = DocumentStore.For(fun store ->
store.Connection(connstring)
let duTy = typeof<DU>
// have to filter out the auto-generated `Tags` static class.
let innerTys = duTy.GetNestedTypes() |> Array.filter (fun t -> t.BaseType = duTy) |> Array.map MappedType.op_Implicit
let mapping = store.Schema.For<DU>()
mapping.AddSubClassHierarchy(innerTys) |> ignore
()
)
store.Schema.ApplyAllConfiguredChangesToDatabase ()
use session = store.LightweightSession()
session.Store(Case1 { id = case1Guid; thing = 10; status = true})
session.Store(Case2 { id = case2Guid; butts = "lol"; ``where`` = DateTime.UtcNow })
session.SaveChanges ()
// the problem is that this works already with Marten.
// we can't name the inner sealed classes of DU.Case1 or DU.Case2, which is the premise of the Marten support for hierarchical support (ie gimme all of these subclass instances)
let one = session.Load<DU>(case1Guid)
let two = session.Load<DU>(case2Guid)
printfn "%A" [one; two]
0
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Marten" Version="2.8.2" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment