Notes on new ASP.NET Core API setup with Swagger, EF Core, SQLite
Today I made a new ASP.NET Core project for a hobby website; these are some notes on what I did which is mainly similar to what I’ve settled on in my past projects.
Use dotnet to make a new web API in the output directory that you want (it will make the directory too):
dotnet new webapi -o GobGuidescd GobGuides
Create a .gitignore file with at least bin/ and obj/.
Now add these packages for Entity Framework Core:
Create a derived DbContext to serve as your application’s database context class, I put mine in a folder/namespace Data:
In the appsettings.Development.json, add some SQLite database connection string to the JSON:
Now edit Program.cs to like this:
I believe InvalidOperationException is a standard practice exception for when configuration data is missing.
This part:
will make it so starting the app executes any outstanding migrations, that would be found in the same assembly and scaffolded with dotnet-ef. If the migrations are in a different assembly, the way the app database context is registered in the services will have to be like this:
The web API project file would also need a project reference to the Infrastructure project.
This is a nice way to setup the Swagger UI to be served at / instead of /swagger, which is convenient for development:
When the app is started, it will create the SQLite database, gob_guides_dev.db in this example. Files gob_guides_dev.db-shm, gob_guides_dev.db-wal will also be created when the database is used; in my case I add all three to the .gitignore.