Monday, October 30, 2017

ASP.NET Core MVC + Web API app with EF Core 2.0 & SQLite

This tutorial uses Visual Studio 2017 and ASP.NET Core 2.0. 

My intention is to give you a practical introduction into developing ASP.NET Core 2.0 MVC and Web API apps with the SQLite database as an alternative to traditional SQL Server.

A useful utility that comes in handy when working with the SQLite database is SQLiteStudio. Download SQLiteStudio from: Extract the ZIP file and place contents in a separate folder. Run SQLiteStudio.exe.

We will build an ASP.NET Core 2.0 app that uses the following Student entity:

ASP.NET Core 2.0 MVC project

In a working directory, create a folder named SQLiteWeb. Change to the SQLiteWeb directory. Try out some of these important .NET Core 2.0 commands:

  1. dotnet --help – this gives you a list of common commands
  2. dotnet restore – restore dependencies specified in the .NET project
  3. dotnet build - Builds a .NET project
  4. dotnet run --help – provides help information about the run command
  5. dotnet new --help – shows the types of templates that can be scaffolded. At the time of writing these are 18 different templates
  6. dotnet new mvc --help – shows switches that can be used when creating an MVC application
We will create an MVC application that uses "Individual authentication" and the SQLite database. 
Execute the following terminal command from within the SQLiteWeb directory: 

dotnet new mvc --auth Individual

A web app is created for you and all Nuget packages are automatically restored. To run the application, 
execute the following command inside the terminal window:

dotnet run

Notice a message similar to the following:

Hosting environment: Production
Content root path: E:\_DEMO\SQLiteWeb
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

As described in the message, point your browser to http://localhost:5000 and you will see the default 
ASP.NET Core page:


This runs your application in a web server called Kestrel that is listening on port 5000. Register a new user.

Stop the web server by hitting Ctrl+C. If you are curious about where the data is saved and the location of the SQLite database, you will find a *.db file located in the bin/Debug/netcoreapp2.0 directory. Have a peek at its contents using the SQLiteStudio utility mentioned earlier in this article.

To open your web application in Visual Studio, start Visual Studio then open the SQLiteWeb.csproj file.

File >> Open >> Project Solution

Hit CTRL + F5 in Visual Studio 2017. This time, the web application will start and will be hosted by IIS Express

When working with ASP.NET Core, you will need to go to the command-line interface frequently. Add a command-prompt extension to make it easier. Click on Tools >> Extensions and Updates


Find an extension named “Open Command Line” as shown below.


If you have not installed it already, install the above extension.

In solution explorer, right-click on the SQLiteWeb node the choose “Open Command Line” >> “Default (cmd)


This opens a regular operating system terminal window. 

The Student class

Inside of the Models folder, add a class file named Student.cs. Use the following code for the class file:

public class Student {
  public int StudentId { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string School { get; set; }
  public DateTime StartDate { get; set; }

Add the following property to the ApplicationDbContext.cs class file located in the Data directory.

  public DbSet<Student> Students { get; set; }

Notice the connection string in the appsettings.json file:

   "ConnectionStrings": {
      "DefaultConnection": "DataSource=app.db"
   "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
         "Default": "Warning"


We are now ready to do some migrations: 
  • Compile your application
  • Open a command terminal inside the  main project SQLiteWeb folder
  • Add a migration to the project with the following ef command:
dotnet ef migrations add "First Migration"

Notice that class files are created in the Data/Migrations folder.
  • We will then update the database with the following terminal command:
dotnet ef database update
You will experience the following error:

SQLite does not support this migration operation ('AddForeignKeyOperation'). For more information, see

This error is caused by the fact the SQLite cannot alter tables and indexes during migration. See this article. The workaround is to comment out all the lines of code in the "Data/Migrations/xxxxxx_First Migration.cs" file that do not pertain to the Students entity. This should be done in both the up() and down() methods. Thereafter, run the "dotnet ef database update" command again and it should complete successfully.

Seed Data

Before we carry out code first migrations, let us first create some seed data: 
  • In the Models folder, create a class named DummyData.cs.
  • Add the following Initialize() method code inside the DummyData class:
public static void Initialize(ApplicationDbContext db) {
  if (!db.Students.Any()) {
    db.Students.Add(new Student {
      FirstName = "Bob",
      LastName = "Doe",
      School = "Engineering",
      StartDate = Convert.ToDateTime("2015/09/09")
    db.Students.Add(new Student {
      FirstName = "Ann",
      LastName = "Lee",
      School = "Medicine",
      StartDate = Convert.ToDateTime("2014/09/09")
    db.Students.Add(new Student {
      FirstName = "Sue",
      LastName = "Douglas",
      School = "Pharmacy",
      StartDate = Convert.ToDateTime("2016/01/01")
    db.Students.Add(new Student {
      FirstName = "Tom",
      LastName = "Brown",
      School = "Business",
      StartDate = Convert.ToDateTime("2015/09/09")
    db.Students.Add(new Student {
      FirstName = "Joe",
      LastName = "Mason",
      School = "Health",
      StartDate = Convert.ToDateTime("2015/01/01")

To generate seed data, we will first inject the dependency “ApplicationDbContext context” into the arguments of the Configure() method in Startup.cs. 
Next, we can make a call to seed the data at the bottom of the Configure() method with the following statement:

At this point, data will not have been seeded yet because this happens when the application is actually run.

Creating an MVC UI

Let us seed the data by running your web application in a browser. You should see the same page as we saw earlier. Let us create a UI so that we can see the seeded data.

  • Right-click on the Controllers folder and choose Add >> New Item… >> Controller...
  • Choose "MVC Controller with views, using Entity Framework" then click on Add.
  • Model Class=Student, Data context class=ApplicationDbContext
Click on Add. If you are asked to save the solution file then accept the default location and save it in your project root folder.

You’ll notice that the controller takes a ApplicationDbContext as a constructor parameter. ASP.NET dependency injection will take care of passing an instance of ApplicationDbContext into your controller.

The controller contains an Index action, which displays all students in the database, and a Create action, which inserts a new student into the database.

  • Let us add a link to the Students controller on the main page of our application. Open _Layout.cshtml under Views/Shared.
  • Paste the following markup in the navigation section around line 36:

<li><a asp-area="" asp-controller="Students" asp-action="Index">Students</a></li>

  • Run the application then click on the Students link. You should see the dummy data that we created.


  • Add a new student to the database.

The WebAPI Controller

Let us add a Web API Studentsapi controller to our projects. 
  • Right-click on the Controllers folder >> Add > Controller...
  • Select "API Controller with actions, using Entity Framework" then click Add.
  • Model class=Student, Data context class=ApplicationDbContext, Controller name=StudentsapiController
  • Click on Add
  • Hit CTRL-F5 on your keyboard and point your browser to /api/studentapi. You will see the seed data appearing as JSON in the browser:

No comments:

Post a Comment