Blazor + EF Core: A Simple Web App Part 1

Morgan Kenyon
The Startup
Published in
11 min readJun 27, 2019
Photo by Connor Jalbert on Unsplash

Entity Framework (EF) Core is Microsoft’s cross platform Object Relational Mapper (ORM). EF Core provides abstractions over different data stores and manages database resources automatically. EF Core targets .NET Core, meaning it’s cross platform, it can run on Windows, Mac and Linux. EF Core shouldn’t be confused with regular Entity Framework (EF), the older .NET Framework version.

Every web app needs a data source, and EF Core is a great way to interact with a SQL database. So lets walk through the process of adding EF Core to an brand new Blazor App.

Other TinRoll Articles

This article is the first in a series about C# and Blazor development. Here are the links to the other articles.

Blazor + EF Core: A Simple Web App Part 2

TinRoll #3: Building Out the API Layer

TinRoll #4: Creating a Generic Repository

Blazor App

Blazor is Microsoft’s new web framework for building front end web apps in C#. It’s in preview release and will be shipping as part of .NET Core 3.0.

Microsoft has great documentation on how to create your first Blazor app. If you don’t want to use Blazor, the steps mentioned here will be practically identical for any other C# .NET Web Api.

Because Blazor is in preview release (at time of writing) I will be using the preview release of EF Core 3. I’m currently running dotnet core 3 preview 5, which you can download here.

Microsoft doesn’t recommend running production apps on preview releases, but they’re good enough to create a simple tutorial.

This tutorial will take you through downloading EF Core, and setting up your Blazor app, and interacting with new APIs via Postman. In a second post we’ll dive more into Blazor front end code and display that data in a web page.

All the code mentioned in this article is available via the project’s github page, specifically in the setup branch of that project.

Setup Blazor

You can follow Microsoft’s Blazor documentation to create a Blazor app. The tutorial was simple to follow with the following words of advice.

1. I had to run Visual Studio in Admin mode (not sure what issue I encountered, but it seemed to fix it)

2. Ensure that Visual Studio allows preview versions of .NET Core SDK.

In Visual Studio navigate to Tools > Options, make sure the option underlined below is turned ON.

After creating the project you can start the solution and you should see the following web page.

This is the default Blazor demo. You click around on the Counter or Fetch Data menu options. Check out the client project to see the razor files that are actually driving the UI. Blazor is a pretty new web framework, so there’s lot of stuff I haven’t seen before.

A Simple Blazor Introduction

Until recently JavaScript was the only programming language natively supported via web browsers. If you wanted something to run in the browser you were more or less forced to use JavaScript.

That has changed recently with the introduction of WebAssembly (wasm).

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

Programming languages can now target wasm knowing that all modern browsers provide full support for it. Programs targeting wasm will be able to run in any browser with native like performance.

Blazor is Microsoft’s UI framework that takes advantage of wasm. It leverages the Mono project’s support for wasm to bring C# to the browser. It gives you another choice for front end programming language rather than JavaScript. As someone who is not a huge JavaScript fan, I’ve been following the development and releases on this framework.

This Blazor app will be a simple stackoverflow clone, tentatively called TinRoll. Now lets get down to business with adding Entity Framework Core to this project.

Data Layer

Our Blazor app does not come with any data layer, so we need to create one. Right click on the solution ‘TinRoll’ and Add a new project.

Pick the Class Library (.NET Standard) option, click next. Name it TinRoll.Data, then click Create.

We have our project, so lets add our Nuget dependencies for EF Core. I’m demoing using Package Manager Console, but you can also right click on projects or use the dotnet cli to add Nuget packages as well.

EF Dependencies

Launch the Package Manager Console in Visual Studio. It’s located at Tools > Nuget Package Manager > Package Manager Console. Once that window opens make sure TinRoll.Server is the default project. And run the following command:

> Install-Package Microsoft.EntityFrameworkCore.Design -Version 3.0.0-preview5.19227.1

This package is required for the startup projects that will be using EF Core. Which in our case in the TinRoll.Server project.

Then change the default project to TinRoll.Data and run the following two commands:

> Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.0.0-preview5.19227.1> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.0.0-preview5.19227.1

The Microsoft.EntityFrameworkCore.SqlServer package pulls in all our dependencies to actually create migrations and manage our database. Though we only manually add one Nuget package, Nuget will add all other needed EF Core dependencies to our project automatically.

The Microsoft.EntityFrameworkCore.Tools package will provide the ability to create migrations from the Package Manager Console. This is new functionality as of EF Core 3.

That finishes our installation of EF Core, now onto Data Entities!

Data Entities

TinRoll is going to be a Stackoverflow clone. So lets setup two entities, a User and a Question entity.

Right click on the TinRoll.Data project, add a new folder called “Entities”. In that folder add two new classes, one called User and the other called Question. Then update each class to resemble the following.

We’ve defined a 1 to many relationship between our User and Question classes. A User is allowed to ask multiple Questions, but each Question only has one User as its author.

Now that we have our entities next lets add our context class. In EF Core the DbContext is the class that manages interactions with our database. If we want to query, insert, update or delete anything in our database those actions will all happen through our TinRollContext class.

Right click on TinRoll.Data and add a new C# class called TinRollContext. And modify it to look like the following:

Each entity class that we’ve defined will correspond to one DbSet reference here. Then each DbSet class we add in this class will correspond to one table getting created in our database. We have two entities and once we create our database we should expect both a Users and a Questions table to appear.

After this step this should be your TinRoll.Data project structure. Now our Data project is all setup. Lets go back to our Server project and ensure all the plumbing is setup to use Entity Framework.

Wiring Everything Up

Open the Startup.cs file in the Server project and add a configuration for our TinRollContext. Ensure the ConfigureServices method matches the following. The AddMvc() and AddResponseCompression lines should already exist. Add lines 9–10 to tell our app we’re using EF Core 3 and where our Database is located.

The connection string tells our app that we will be using a local database. In a production system you would want to move the connection string to a config file and use an actual standalone SQL database, but that will do for now. You’ll have to import some files and add a reference to the TinRoll.Data project.

After those are all imported, build the solution to check that everything is setup correctly. Next lets add a migration!

First Migration

Migrations are instructions to EF Core that describe how to create and delete items in our SQL Database. Anything that you want to add to the database will first be added to a migration. Then that migration will be run which updates the database.

Re-open the Package Manager Console. Ensure that TinRoll.Data is the default project and run the following command.

> Add-Migration Initial

After this completes you’ll see a new migration folder in your data project. Every time you add a migration, a new migration file will be generated. You can open up the initial migration file and take a look.

Every migration file has both an Up and Down method. When the Up method gets run, the changes in the migration are being applied to the database. When the Down method gets run, the changes in the migration are removed from the database.

If you’re familiar with SQL, in the Up() method you’ll see C# methods to create tables, add primary keys, add foreign keys, etc. Everything we want to happen when we apply this migration. Then in the Down() method it drops both tables that were created in the Up() method.

The other file that was generated is the snapshot file. Unlike the migration files, there will only ever be one snapshot file. It describes the current state of all the data entities that exists in your project. It’s a C# representation of what your current database structure should be.

Now lets apply that migration to our database. Navigate back to Package Manager Console and run:

> Update-Database

EF Core will automatically create the database specified in the connection string if it does not already exist. So this Update-Database command creates our database and applies our first migration. Everything contained in our Up() method now exists in our database.

Now if you view our database via Sql Server Object Explorer the TinRollDb should be present with three tables:

The two tables we created and a EFMigrationsHistory table. What is that?

EF Core uses this table to keep track of which migrations have been applied to this database. Selecting from the table shows our initial migration is the only record.

I strongly recommend that you never modify this table. EF Core manages the SQL database and this table automatically. Manual changes can potentially confuse EF Core and move your database into a state that EF Core cannot fix.

Congratulations! You’ve leveraged EF Core to create a SQL database without writing any raw SQL. Now that we have our database, lets write something to connect to it!

Controller

By default Blazor ships with a SampleDataController. Lets add two more controllers to create and view our Users and Questions. Right click on your controller folder, add controller and name it UsersController. Let’s create two actions, one to get users and one to create users.

Lets create a QuestionsController that looks very similar:

On both controllers, these two actions allow us to create and access our User and Question entities. This is the beginning of the Create, Read, Update and Delete (CRUD) controller actions. This is a very common pattern if you follow the REST paradigm/architecture to design your APIs.

It’s worth noting that accessing the data layer in a Controller file breaks a lot of architectural principles. I wouldn’t want to ship code to Production that contained code organized like this. But since this is a getting started tutorial, I’m taking some liberties that I wouldn’t normally make.

Now that both of those are added, lets restart our app. It should open on the same UI page as before. Lets modify our endpoint in order to test out our new controller actions.

Append “/api/users” to the end of whatever url just popped up:

http://localhost:1059/ => http://localhost:1059/api/users

Note: the port number of your url may be different, don’t copy the above link, just use whatever popped up on your browser.

And you should see an empty json list appear. That means we connected to the database and returned 0 results. Which makes sense because we haven’t created any users yet.

In order to more fully test our APIs without diving into the UI layer right now, lets move over to Postman.

Postman

Postman is a great tool for interacting with APIs. As a developer it makes my life so much easier. We can use it to simulate the API calls that our UI will eventually make, but without needing to bother with the UI. We’ll create a couple requests using Postman to test our endpoints. You can download Postman from here.

Once downloaded lets create a collection and some requests. On the top left click “New Collection” and name it TinRoll_Collection. Then click the three button icon on the collection, then on the pop up click “Add Request”. Name the request “Get Users” and input the url that popped up just a moment ago.

https://localhost:1059/api/users

Click run and you should see the same empty json block return in the body of the Postman request. You just made the same request your browser made, but with Postman.

Now lets add a request called “Create User”. Change the HTTP Request Method to “POST” and copy the following json data into the body of the request.

Click “Send”, ensure you got a 200 back, then go back to the GetUsers request and trigger that one again. Now you should see your new user displayed with an Id of 1.

You can create as many users as you want and you’ll see those users added to the results of the GetUsers call.

Now lets create a second pair of requests for our questions. Add a new request and this time call it “Get Questions”. Copy in your url changing the last word from users to questions.

https://localhost:1059/api/questions

Again, since we haven’t added any questions let it should return an empty list. Add a second request called “Create Question”.. Change the HTTP Request Method to “POST” and adding the following json into the body of the request.

Click “Send”, if you get a 200 response back that means your question was created. Return to the “Get Questions” request and that should now return the question that was just created.

(A copy of the Postman collection is also included in the github project library for reference.)

Closing Thoughts

Congratulations! You’ve created a Blazor app that can persist things into a SQL Database using EF Core 3 with the ability to test using Postman!!!

That’s a lot of progress in one article. In the next article we’ll get a full UI to database working. We’ll add a couple migrations to improve our data model. Then we’ll also modify our razor pages to display data in our UI! Stay tuned!

I’m Morgan Kenyon. I’m a .NET developer working in the DFW area. I find C# a great language to use and it’s also backed by a great ecosystem, I love solving hard problems and want to continue talking about the tech I use. If you found this article helpful or thought provoking leave a comment and lets connect over LinkedIn!

Github Project

--

--

Morgan Kenyon
The Startup

I’m a software developer who works with the Microsoft stack. I love to program and write about what I’m doing!