Introduction
Blazor is a new framework built by Microsoft for creating interactive client-side web UI with a .NET codebase. We can write both client-side and server-side code in C#.NET itself. I have already written two articles about the Blazor server on C# Corner. Please refer to the below articles for more basics about the Blazor framework.
- Create A Simple Blazor Server Application With .NET Core 3.0
- Create a Single Page App with Blazor Server and Entity Framework Core 3.0
Traditionally, in monolithic applications, we are using a single database server for the entire application. However, I am combining SQL database and MongoDB in the same application. This application will be a combination of RDBMS and No SQL databases. We will create a Blazor app from scratch and create a SQL database and a table using data migration. We will use this SQL DB to save employee data. We will use the MongoDB database to save City data. You can use the same approach for other .NET Core 3.0 applications also. We can see all the actions step by step.
Prerequisites
- Visual Studio 2019 (version 16.3 or later)
- .NET Core SDK 3.0
- MongoDB Server
Create a Blazor application in Visual Studio 2019
We can create a Blazor app in Visual Studio 2019 using the Blazor server template.

We must install the below libraries to our project. We can use NuGet to install these libraries.
- “Microsoft.EntityFrameworkCore.SqlServer”
- “Microsoft.EntityFrameworkCore.Tools”
- “MongoDB.Driver”
We can create an “Employee” class inside the “Data” folder with below properties.
Employee.cs
namespace BlazorSQLAndMongoDB.Data
{
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Designation { get; set; }
public string Company { get; set; }
public string City { get; set; }
}
}
We can create a “SqlDbContext” class inside the Data folder for entity framework-related operations.
SqlDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace BlazorSQLAndMongoDB.Data
{
public class SqlDbContext : DbContext
{
public SqlDbContext(DbContextOptions<SqlDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
}
We can create a connection string in “appsettings.json” for the SQL database.

We have used a local SQL server, which is available with Visual Studio to create a database and table. You can use any SQL server at your convenience.
We must register the SqlDbContext class inside the “ConfigureServices” method in the Startup class.

Create SQL database and table using entity framework and data migration
We can use the NuGet Package Manager Console from the Tools menu and use the below migration commands to create an SQL database and table.
add-migration Initial
The above command will create a migration script class inside the “Migrations” folder with the current timestamp suffix.
We can use the below command to create a database and table.
update-database
The database and table will be created shortly.
We can create an “IEmployeeService“ interface and declare the below methods inside the interface.
IEmployeeService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BlazorSQLAndMongoDB.Data
{
public interface IEmployeeService
{
Task<List<Employee>> GetEmployees();
Task<bool> CreateEmployee(Employee employee);
Task<bool> EditEmployee(string id, Employee employee);
Task<Employee> SingleEmployee(string id);
Task<bool> DeleteEmployee(string id);
}
}
We can implement the above methods from the interface in another class “EmployeeService”
EmployeeService.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BlazorSQLAndMongoDB.Data
{
public class EmployeeService : IEmployeeService
{
private readonly SqlDbContext _dbContext;
public EmployeeService(SqlDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<List<Employee>> GetEmployees()
{
return await _dbContext.Employees.ToListAsync();
}
public async Task<bool> CreateEmployee(Employee employee)
{
employee.Id = Guid.NewGuid().ToString();
_dbContext.Add(employee);
try
{
await _dbContext.SaveChangesAsync();
return true;
}
catch (DbUpdateException)
{
return false;
}
}
public async Task<Employee> SingleEmployee(string id)
{
return await _dbContext.Employees.FindAsync(id);
}
public async Task<bool> EditEmployee(string id, Employee employee)
{
if (id != employee.Id)
{
return false;
}
_dbContext.Entry(employee).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
return true;
}
public async Task<bool> DeleteEmployee(string id)
{
var employee = await _dbContext.Employees.FindAsync(id);
if (employee == null)
{
return false;
}
_dbContext.Employees.Remove(employee);
await _dbContext.SaveChangesAsync();
return true;
}
}
}
We have added all logic for CRUD operations inside the service class. Please note that you can even create this service without an interface.
We can create a City class with the below properties. City data will be stored in MongoDB.
City.cs
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace BlazorSQLAndMongoDB.Data
{
public class City
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public string State { get; set; }
}
}
We can keep the MongoDB connection string, database name, and collection name inside the appsettings.json file instead of hard coding the values.

We must create an interface and class for reading the values from the appsettings.json file.
We can create the “IMongoDbSettings” interface and declare the below properties.
IMongoDbSettings.cs
namespace BlazorSQLAndMongoDB.Data
{
public interface IMongoDbSettings
{
string CollectionName { get; set; }
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
}
We can create the “MongoDbSettings” class and inherit the IMongoDbSettings interface inside the class.
MongoDbSettings.cs
namespace BlazorSQLAndMongoDB.Data
{
public class MongoDbSettings : IMongoDbSettings
{
public string CollectionName { get; set; }
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
}
We can register this interface and class inside the ConfigureServices class in the Startup class.

We can create an “ICityService“ interface and declare the below methods inside the interface.
ICityService.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BlazorSQLAndMongoDB.Data
{
public interface ICityService
{
Task<List<City>> GetCities();
Task<bool> CreateCity(City city);
Task<bool> EditCity(string id, City city);
Task<City> SingleCity(string id);
Task<bool> DeleteCity(string id);
}
}
We can implement the above methods from the interface in another class “CityService”
CityService.cs
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace BlazorSQLAndMongoDB.Data
{
public class CityService : ICityService
{
private readonly IMongoCollection<City> _cities;
public CityService(IMongoDbSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_cities = database.GetCollection<City>(settings.CollectionName);
}
public async Task<bool> CreateCity(City city)
{
try
{
await _cities.InsertOneAsync(city);
return true;
}
catch
{
return false;
}
}
public async Task<bool> DeleteCity(string id)
{
try
{
await _cities.DeleteOneAsync(city => city.Id == id);
return true;
}
catch
{
return false;
}
}
public async Task<bool> EditCity(string id, City city)
{
try
{
await _cities.ReplaceOneAsync(book => book.Id == id, city);
return true;
}
catch
{
return false;
}
}
public async Task<List<City>> GetCities()
{
try
{
return await _cities.Find(city => true).ToListAsync();
}
catch
{
return null;
}
}
public async Task<City> SingleCity(string id)
{
try
{
return await _cities.Find<City>(city => city.Id == id).FirstOrDefaultAsync();
}
catch
{
return null;
}
}
}
}
We have injected the IMongoDbSettings interface in the above class and fetched MongoDB configuration values from the appsettings.json file.
We have added all logic for CRUD actions for the City entity inside the above service class.
We can register both Employee service and City service in the Startup class.

We can enable detailed circuit errors for the Blazor server application also in the startup class.
ConfigureServices (method)
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddDbContext<SqlDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlDbContext")));
services.Configure<MongoDbSettings>(Configuration.GetSection(nameof(MongoDbSettings)));
services.AddSingleton<IMongoDbSettings>(sp => sp.GetRequiredService<IOptions<MongoDbSettings>>().Value);
services.AddScoped<IEmployeeService, EmployeeService>();
services.AddScoped<ICityService, CityService>();
services.AddServerSideBlazor().AddCircuitOptions(o => o.DetailedErrors = true);
}
We have completed the backend part of the Blazor application. We can create all razor components inside the “Pages” folder for CRUD operations.
We can create components for City first.
ListCities.razor






Ben HayatPosted Jan 26, 2020, 8:14 PM
Nice work!
Jean SinopePosted Nov 12, 2019, 6:19 PM
Wonderful article, very interesting and useful.
Chittaranjan SwainPosted Nov 10, 2019, 6:09 PM
Super article.....