EntityFramework in F# on .NET Core

There is a lot of scattered information these days on using EntityFramework with .NET Core, especially when it comes to F#, so I put this together as a very quick example of the steps.

First, Set up your .NET Core .fsproj with needed packages:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL or whatever DB driver you use

In some module, make your DB types and a DbContext to hold them:

open Microsoft.EntityFrameworkCore

// First, your "code-first" models:
[<Table("some_things",Schema="public")>] // Schema needed for Postgres, YMMV
type SomeThing () = 
  member val ID : System.Guid = System.Guid() with get, set
  member val Name : string = "" with get, set

// Then a type to inherit from DbContext with properties for your models:
type Db (connectionString : string) =
  inherit DbContext()

  val mutable Somethings : DbSet<SomeEntity>
  member public this.SomeThings
    with get() = this.somethings
    and set s = this.somethings <- s

Finally, use the DbContext with an F# query expression, and in an async expression if you like:

async {
  use db = new Db (connectionString)
  let q = query {
    for s in db.Somethings do
    select s
  let! records = q.ToListAsync () |> Async.AwaitTask

I hope this helps readers to get started quickly with the EntityFramework on F# and .NET Core.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s