Repository navigation
Database
Database connection for the MKCards web app. This guide focuses on the development environment.
First, we need a running database. For local testing, we use MariaDB - one of the most popular open-source relational databases, created by the original developers of MySQL.
To run MariaDB locally using Docker, execute the following commands in your terminal. You can choose a different password or database name if desired. The default user is root.
docker pull mariadb
docker run --name mydb -e MYSQL_ROOT_PASSWORD=admin -p 3306:3306 -d mariadb
To inspect the database (e.g. list tables, run queries), you can use the mariadb CLI tool (available on most Linux distributions). Use this command to connect to the running MariaDB container:
mariadb --host=localhost -P 3306 -u root -p
Then, you can navigate and inspect your database using standard SQL commands:
SHOW DATABASES;
USE mydb;
SHOW TABLES;
With the database running, we now need to connect our application to it. This is done using a connection string, defined in the MKCards\MKCards.Server\appsettings.json. In our case, it should look like this:
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user=root;password=admin;database=mydb"
}
Note that connection in set up in MKCards\MKCards.Server\Program.cs, where we use IDbContextOptionsBuilder to allow different implementations based on database used:
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
IDbContextOptionsBuilder dbContextOptionsBuilder = new MariaDbContextOptionsBuilder(connectionString, new Version(11, 8, 2));
builder.Services.AddDbContext<ApplicationDbContext>(dbContextOptionsBuilder.GetConfiguration());
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
Entity Framework Core uses migrations to create and update the database schema based on your data models.
To create and apply the initial migration, navigate to the MKCards.Server folder in your terminal and run:
dotnet ef migrations add InitialCreate
dotnet ef database update
These commands:
- Generate SQL code from C# data models,
- apply the generated schema to the connected MariaDB database.
However, note that our repository already contains up-to-date migrations for MariaDB (MySQL), so generating new migrations might be needed only for different database system, such as Microsoft SQL Server.
What's more, our code applies all migrations automatically. So in case you use MySQL, you can run web server with no commands for migrations at all!
At this point, you should be able to run the local web application connected to your MariaDB instance. This tutorial focuses on the development setup. For production, the process may differ, but typically the only required change is the connection string (to point to the production database server).
Links:
https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql