Skip to content

Instantly share code, notes, and snippets.

@Luiz-Monad
Last active January 31, 2018 01:32
Show Gist options
  • Save Luiz-Monad/b226cc586d321d3babce14988ffc0baf to your computer and use it in GitHub Desktop.
Save Luiz-Monad/b226cc586d321d3babce14988ffc0baf to your computer and use it in GitHub Desktop.
HighOrder EntityFramework
//how to implement CRUD with F# and entityframework and TypeClasses
//transform this into an highorder type
type Customer with static member queryId = <@ fun ( λ : Customer ) -> λ.Id @>
//just a helper
type entity<'T> = ('T -> int)
//our highorder context
type EntitySet<'T when 'T : not struct> = {
context : Entities
getId : entity<'T>
} with
member this.FindById id = <@ query { //we love AST, dont we?
from entity in this.context.Set<'T> () do
where ( (%this.queryId) entity = id )
select entity } @> |> runQuery |> Seq.toList
//lets upgrade the boring entityframework to a kind of typeclass
let inline entitySet ( context : Entities ) ( template : ^T option ) = {
context = context
getId = getId
queryId = (^T : (static member queryId : Expr<('T -> int)>) ()) //almost like row polimorphism
}
//yes, this is MVC
let inline controller ( context : Entities ) ( operation : 'T Operation ) =
let table = entitySet context None
match operation with
| Get ( Some id ) -> table.FindById id |> Seq.singleton
| Get ( None ) -> table.List ()
| Post ( entity ) -> table.AddOrUpdate entity; Seq.empty
| Delete ( entity ) -> table.Delete entity; Seq.empty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment