Introduction to using Entity Framework with SQL Express and F# Console Apps and Web APIs
Updated: 03 September 2023
Foreword, migrations don’t work with F# (maybe some time but no hopes)
Create the Database
Because we can’t quite work with the normal EF Migrations we can either use C# to manage our data layer as per this article buuuuut I don’t really want to do that, so let’s just use SQL for now. Generally though I feel like maybe EF is not the way to go with F# but for the purpose of discussion
And then run the following query on the database
Console App
Create a new console app, you can do this using Visual Studio or the dotnet cli
Adding the Types
Assuming we have a database that’s already configured and we want to add mappings for our application we beed to define the type as well as the context
Using the Context
Next we can just make use of the DbContext that we created to access the database as we usually would using EF
Web API
IF we want to use it with a Web API we can do that pretty much the same as above, however we’ll set up the DBContext as a service so it can be used with Dependency Injection
Set Up the Types
We’ll use the same type setup as in the console app but but note that we make the type public. We can define this in a file called Person.fs, ensure this is the topmost file in your project
Note also that we’ve updated the type to make use of the DbContextOptionsBuilder and that we’re not going to override the OnConfiguring method as we’ll be using the service setup
Service Configuration
In our startup file we can configure the service in the ConfigureServices method, I’ve just left that part of the Startup.fs file below
Usage
If we want to make use of the DBContext we can just reference it a controller’s constructor as a dependency
And we can define some routes that make use of this within the PersonController type
And this will allow you to make use of the provided endpoints on your application using either of the following:
GET /person/<ID>
POST /person
If we would also like to verify if these records are being created in the database we can run: