Introduction
In this article, we will create a Blazor application using Google Firestore as a database provider. We will create a Single Page Application (SPA) and perform CRUD operations on it. We will use Bootstrap 4 to display a modal popup for handling user inputs. The form also has a dropdown list which will bind to a collection in our database. We will also implement a client-side search functionality to search the employee list by employee name.
Take a look at the final application.

Prerequisites
- Install the .NET Core 2.1 SDK from here.
- Install the latest version of Visual Studio 2017 from here.
- Install the ASP.NET Core Blazor Language Services extension from here.
Source Code
Get the source code from GitHub.
Configuring Cloud Firestore
The first step is to create a project in the Google Firebase console. Navigate to https://console.firebase.google.com and sign in with your Google account. Click on the Add Project link. A pop-up window will open as shown in the image below. Provide your project name and click on the "Create project" button at the bottom.

Note the project ID here. Firebase project IDs are globally unique. You can edit your project ID while creating a new project. Once the project is created you cannot change your project Id. We will use this project ID in the next section while initializing our application.
Click on the project you just created. A "Project Overview" page will open. Select “Database” from the left menu. Then, click the “Create database” button. A pop-up window will open asking you to select the “Security rules for Cloud Firestore”. Select “Start in locked mode” and click on "Enable".
Refer to the image below.

This will enable the database for your project. Firebase project has two options for the database – Real-time Database and Cloud Firestore. For this application, we will use the “Cloud Firestore” database. Click on the “Database” dropdown at the top of the page and select “Cloud Firestore”.

We will create a city collection to store the city name for employees. We will also bind this collection to a dropdown list in our web application from which the user will select the desired city. Click on “Add collection”. Set the collection ID as “cities”. Click on “Next”. Refer to the image below.

Put the field value as “CityName”, select the string from the Type dropdown, and fill the value with the city name as “Mumbai”. Click on "Save".

This will create the “cities” collection and insert the first document in it. Similarly, create four more documents inside this collection and put the “CityName” value as Chennai, New Delhi, Bengaluru, and Hyderabad.
We will use the “employees” collection to store employee data, but we will not create it manually. We will create an “employees” collection while adding the first employee data from the application.
Configuring Google Application Credentials
To access the database from our project, we need to set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to a JSON service account key file. This will set an authentication pipeline from our application to the cloud Firestore.
To generate the service account key file, follow the steps mentioned below.
Step1. Navigate hereto log in with the same Google account that you have used to create Firestore DB.
Step2. Select Project from the dropdown in the menu bar at the top.
Step3. Select “Service accounts” from the left menu. Select the service account for which you want to create the key. Click on the More button in the “Actions” column in that row, and then click the "Create key".
Refer to the image below.

Step4. A popup modal will open asking you to select the key type. Select “JSON” and click on the "Create" button. This will create a private key for accessing your Firestore account and download a JSON key file to your machine. We will use this file to set the GOOGLE_APPLICATION_CREDENTIALS environment variable in the later part of this article.
Create a Blazor Web Application
Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select .NET Core inside the Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from the available project types. Put the name of the project as BlazorWithFirestore and press OK.

After clicking on OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.1” from these dropdowns. Then, select the “Blazor (ASP .NET Core hosted)” template and press OK.

Now, our Blazor solution will be created. You can observe that we have three project files created in this solution.
- BlazorWithFirestore.Client – It has the client-side code and contains the pages that will be rendered on the browser.
- BlazorWithFirestore.Server – It has the server-side codes such as the data access layer and web API.
- BlazorWithFirestore.Shared – It contains the shared code that can be accessed by both client and server. It contains our Model classes.
Adding Package reference for Firestore
We need to add the package reference for Google Cloud Firestore, which will allow us to access our DB from the Blazor application. Right-click on BlazorWithFirestore.Shared project. Select “Edit BlazorWithFirestore.Shared.csproj”. It will open the BlazorWithFirestore.Shared.csproj file. Add the following lines inside it.
<ItemGroup>
<PackageReference Include="Google.Cloud.Firestore" Version="1.0.0-beta14" />
</ItemGroup>
Similarly, add these lines to BlazorWithFirestore.Server.csproj file also.
Creating the Model
We will create our model class in BlazorWithFirestore.Shared project. Right-click on BlazorWithFirestore.Shared and select Add >> New Folder. Name the folder as Models. Again, right-click on the Models folder and select Add >> Class to add a new class file. Put the name of your class as Employee. cs and click Add.
Open the Employee. cs class and put the following code into it.
using System;
using Google.Cloud.Firestore;
namespace BlazorWithFirestore.Shared.Models
{
[FirestoreData]
public class Employee
{
public string EmployeeId { get; set; }
public DateTime date { get; set; }
[FirestoreProperty]
public string EmployeeName { get; set; }
[FirestoreProperty]
public string CityName { get; set; }
[FirestoreProperty]
public string Designation { get; set; }
[FirestoreProperty]
public string Gender { get; set; }
}
}
We have decorated the class with the [FirestoreData] attribute. This will allow us to map this class object to the Firestore collection. Only those class properties, that are marked with the [FirestoreProperty] attribute, are considered when we are saving the document to our collection. We do not need to save EmployeeId to our database as it is generated automatically. While fetching the data, we will bind the auto-generated document ID to the EmployeeId property. Similarly, we will use the date property to bind the created date of collection while fetching the record. We will use this date property to sort the list of employees by created date. Hence, we have not applied the [FirestoreProperty] attribute to these two properties.
Similarly, create a class file Cities. cs and put the following code into it.
using System;
using Google.Cloud.Firestore;
namespace BlazorWithFirestore.Shared.Models
{
[FirestoreData]
public class Employee
{
public string EmployeeId { get; set; }
public DateTime date { get; set; }
[FirestoreProperty] public string EmployeeName { get; set; }
[FirestoreProperty] public string CityName { get; set; }
[FirestoreProperty] public string Designation { get; set; }
[FirestoreProperty] public string Gender { get; set; }
}
}
Creating a Data Access Layer for the Application
Right-click on the BlazorWithFirestore.Server project and then select Add >> New Folder and name the folder as DataAccess. We will be adding our class to handle the database-related operations inside this folder only. Right-click on the DataAccess folder and select Add >> Class. Name your class EmployeeDataAccessLayer.cs.
Put the following code inside this class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlazorWithFirestore.Shared.Models;
using Google.Cloud.Firestore;
using Newtonsoft.Json;
namespace BlazorWithFirestore.Server.DataAccess
{
public class EmployeeDataAccessLayer
{
string projectId;
FirestoreDb fireStoreDb;
public EmployeeDataAccessLayer()
{
string filepath = "C:\\FirestoreAPIKey\\blazorwithfirestore-6d0a096b0174.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", filepath);
projectId = "blazorwithfirestore";
fireStoreDb = FirestoreDb.Create(projectId);
}
public async Task<List<Employee>> GetAllEmployees()
{
try
{
Query employeeQuery = fireStoreDb.Collection("employees");
QuerySnapshot employeeQuerySnapshot = await employeeQuery.GetSnapshotAsync();
List<Employee> lstEmployee = new List<Employee>();
foreach (DocumentSnapshot documentSnapshot in employeeQuerySnapshot.Documents)
{
if (documentSnapshot.Exists)
{
Dictionary<string, object> city = documentSnapshot.ToDictionary();
string json = JsonConvert.SerializeObject(city);
Employee newuser = JsonConvert.DeserializeObject<Employee>(json);
newuser.EmployeeId = documentSnapshot.Id;
newuser.date = documentSnapshot.CreateTime.Value.ToDateTime();
lstEmployee.Add(newuser);
}
}
List<Employee> sortedEmployeeList = lstEmployee.OrderBy(x => x.date).ToList();
return sortedEmployeeList;
}
catch
{
throw;
}
}
public async void AddEmployee(Employee employee)
{
try
{
CollectionReference colRef = fireStoreDb.Collection("employees");
await colRef.AddAsync(employee);
}
catch
{
throw;
}
}
public async void UpdateEmployee(Employee employee)
{
try
{
DocumentReference empRef = fireStoreDb.Collection("employees").Document(employee.EmployeeId);
await empRef.SetAsync(employee, SetOptions.Overwrite);
}
catch
{
throw;
}
}
public async Task<Employee> GetEmployeeData(string id)
{
try
{
DocumentReference docRef = fireStoreDb.Collection("employees").Document(id);
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
if (snapshot.Exists)
{
Employee emp = snapshot.ConvertTo<Employee>();
emp.EmployeeId = snapshot.Id;
return emp;
}
else
{
return new Employee();
}
}
catch
{
throw;
}
}
public async void DeleteEmployee(string id)
{
try
{
DocumentReference empRef = fireStoreDb.Collection("employees").Document(id);
await empRef.DeleteAsync();
}
catch
{
throw;
}
}
public async Task<List<Cities>> GetCityData()
{
try
{
Query citiesQuery = fireStoreDb.Collection("cities");
QuerySnapshot citiesQuerySnapshot = await citiesQuery.GetSnapshotAsync();
List<Cities> lstCity = new List<Cities>();
foreach (DocumentSnapshot documentSnapshot in citiesQuerySnapshot.Documents)
{
if (documentSnapshot.Exists)
{
Dictionary<string, object> city = documentSnapshot.ToDictionary();
string json = JsonConvert.SerializeObject(city);
Cities newCity = JsonConvert.DeserializeObject<Cities>(json);
lstCity.Add(newCity);
}
}
return lstCity;
}
catch
{
throw;
}
}
}
}
In the constructor of this class, we are setting the GOOGLE_APPLICATION_CREDENTIALS environment variable. You need to set the value of the file path variable to the path where the JSON service account key file is located in your machine. Remember we downloaded this file in the previous section. The projectId variable should be set to the project ID of your Firebase project.
We have also defined the methods for performing CRUD operations. The GetAllEmployees method will fetch the list of all employee documents from our “employees” collection. It will return the employee list sorted by document creation date.
The AddEmployee method will add a new employee document to our “employees” collection. If the collection does not exist, it will create the collection first and then insert a new document in it.
The UpdateEmployee method will update the field values of an already existing employee document, based on the employee ID passed to it. We are binding the document ID to the employee property, hence we can easily manipulate the documents.



hemant fegadePosted Feb 24, 2020, 6:26 AM
Hi dear , i want the to access sub collection dynamically using mvc how should i do this ?
Ben HayatPosted Apr 16, 2019, 1:49 AM
I wish you would re-do this project with the NEW Razor Component syntax and model. Your code is kind of outdated.
Ben HayatPosted Apr 15, 2019, 9:48 PM
Could you please make an article how to use Firebase Auth with Razor Component? How we can add new user and be able authenticate them and get the token at server side for authorization.
Ben HayatPosted Apr 15, 2019, 9:46 PM
Great Article Ankit;
Madhv KushawahPosted Mar 24, 2019, 1:28 PM
Nice Article to understand Firestore.