Using Firebase Cloud Firestore Database in .NET Projects

Beyza Ozgur
4 min readJun 12, 2024

--

Firestore is a real-time, serverless, NoSQL database that stores data in documents organized into collections. It can be easily integrated into projects using Firebase SDKs. This post will demonstrate how to create and connect a new Firestore database to a .NET web application.

Creating a Database & Adding Collections and Documents

Create a new project on Firebase Console.

After project creation, select Firestore Database from the left menu and create a new database.

Add a new collection to store your data.

Add a new document to the collection to store the fields you need. Select field types and enter the values for your record.

Congrats! You have added your first record. After adding a few documents, your database table will look like this.

Information Needed for .NET Integration

To connect to the Firestore Database from the .NET project, we need to obtain the Project ID value and JSON file that contains a private key.

Go to project settings and note your Project ID.

Select the Service Accounts tab from project settings and generate a private key.

It will automatically start to download the .json file that we need for integration. Let’s rename it to serviceAccountKey.json to make it easily readable.

Adding Firestore Database Service to .NET Web Application Project

Install FirebaseAdmin and Google.Cloud.Firestore packages to the .NET project.

dotnet add package FirebaseAdmin
dotnet add package Google.Cloud.Firestore

Modify Program.cs file.

// Set environment variable for Google credentials (use private key json file’s path)
var credentialPath = Path.Combine(Directory.GetCurrentDirectory(), "Configurations", "serviceAccountKey.json");
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credentialPath);

// Initialize Firebase Admin SDK
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.GetApplicationDefault()
});

// Add Firestore DB Service (use Project ID)
builder.Services.AddSingleton(FirestoreDb.Create("beyzasproject"));

Create a User model to map the database fields.

namespace FirestoreDatabaseProject.Models
{
public class User
{
public string Username { get; set; }
public string Name { get; set; }
public string Occupation { get; set; }
public DateTime RegisterDate { get; set; }
public bool IsActive { get; set; }

}
}

Get the list of your records inside the controller method and send the user list to the view.

public class HomeController : Controller
{
private readonly FirestoreDb _firestoreDb;

public HomeController(FirestoreDb firestoreDb)
{
_firestoreDb = firestoreDb;
}

public async Task<IActionResult> Index()
{
var users = new List<User>();

try
{
// get users collection
var usersCollection = _firestoreDb.Collection("users");

if (usersCollection != null)
{
// get records/rows of users table
var userList = await usersCollection.GetSnapshotAsync();

foreach (var user in userList.Documents)
{
// create user object using the fields of the record
User u = new User();
u.Username = user.GetValue<string>("Username");
u.Name = user.GetValue<string>("Name");
u.Occupation = user.GetValue<string>("Occupation");
u.RegisterDate = user.GetValue<DateTime>("RegisterDate");
u.IsActive = user.GetValue<bool>("IsActive");

// add to users list
users.Add(u);
}
}

}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}

return View(users);
}
}

Let’s create a table to display user list data in the view.

@model List<User>

<table class="table">
<thead>
<tr>
<th scope="col">User Name</th>
<th scope="col">Name</th>
<th scope="col">Occupation</th>
<th scope="col">Register Date</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
@foreach(var user in Model)
{
<tr>
<td>@user.Username</td>
<td>@user.Name</td>
<td>@user.Occupation</td>
<td>@user.RegisterDate</td>
<td>@(user.IsActive ? "Active" : "Passive")</td>
</tr>
}
</tbody>
</table>

Here is the final result:

Using Firebase Cloud Firestore with a .NET web application is a powerful combination for creating real-time, serverless, and scalable applications. By following these steps, you can easily set up Firestore and integrate it into your .NET project to manage and display your data effectively.

--

--