TAGS :Viewed: 10 - Published at: a few seconds ago
MICROSERVICES .NET CORE WITH EXAMPLE — Part 4
Source: internet
A fundamental characteristic of microservices is each autonomous service maps to its own database, rather than a shared database. This approach reduces the risk associated with a single, monolithic database, and make it more flexible in building each service.
Basically, there are 2 types of databases: relational database and non-relational database. We can choose the suitable one for each microservice depended on our purposes.
We are going to use both types of databases in KCommerse project
Relational database with PostgreSQL
Non-relational database with MongoDB
They are both in top 10 trending databases so far
PostgreSQL
PostgreSQL is an ACID-compliant Object Relational Database Management System (ORDBMS). It runs on nearly any operating system including Linux, Unix, Mac OS and Windows.
There are 2 main ways to connect PostgreSQL (we can combine 2 ways in one project):
Use Marten library with the ability to easily use PostgreSQL as a fully fledged document database
Use Object Relational Mapping (ORM) framework to map object entities (such as properties and classes) to relational entities (such as tables and columns) of a database. The option we choose is Microsoft Entity Framework
Preparation steps:
1. Download PostgreSQL here
2. Add connection string in appsettings.json
Sample connection string
Use Marten library
Marten is a client library for .NET that enables you to use PostgresSQL database in two ways:
As a document database
As a event sourcing database
We will focus on document database with Marten in this part. Event sourcing is quite complex, you can check it out in Part 5.
Now let’s start to see how simple it is to implement Marten
1. Install package
Marten
2. Create models (can consider they are as tables)
Sample model
Chat room
3. Create data access for Marten
Startup.cs
4. Create test controller for testing
You can see the result when testing below
Add room
Postman test
Table (auto generated) and data
Find room
Postman
Use Entity Framwork (EF)
We can use EFCore in an application in two different ways: Code-First approach and Database-First approach, and I prefer to use Code-First for KCommerce project
Let’s get the ball rolling!
1. Install these packages
Npgsql.EntityFrameworkCore.PostgreSQL Microsoft.EntityFrameworkCore.Design Microsoft.EntityFrameworkCore.Tools
2. Create models
Hereby the sample Catalog model, you can see full models in source codes
3. Create DbContext
Each database models is derived from Entity model which has primary key type is Guid. In order to make this key generated, we are using Hi/Lo algorithm by:
modelBuilder.UseHiLo();
4. Add additional configuration in Startup.cs
5. Create database
Open Nuget package manager console
Run command: add-migration initial
Run command: update-database
6. Check the database created in pgAdmin (PostgreSQL management tool)
7. Whenever you add a new model (table), just add it in the DbContext file and then reference step 3
MongoDB
MongoDB is a NoSQL document-oriented database that allows you to define JSON based documents which are schema independent.
The schema can be considered as Tables in a Relational Database. A schema in MongoDB is called as collection, and a record in this schema is called as document
Let’s get started
1. Install MongoDB here
2. Install Robo 3T here: tool to interact with your data through visual indicators instead of a text-based interface
3. MongoDB configuration
Update mongod.cfg file in bin folder, contains setting path to the data folder for MongoDB server, as well as to the MongoDB log file, initially without any authentication (change the paths to yours)
Start MongoDB server by command
"C:\Program Files\MongoDB\Server\4.2\bin\mongod.exe" --config "[Path to mongod.cfg]"
If you’re using Windows then you can start MongoDB server from services
Run mongo.exe in command prompt to add the administrator user to the database
4. Open Robo 3T to check connection
Open Robo 3T
Choose “Create” the connection
Follow these steps to configure the connection (you can change the names)
Configure connection
Configure authentication
You can choose Test to check the configuration, then Save and open that connection
Robo 3T UI
5. Install MongoDB .NET Driver: using Nuget and search for MongoDB.Driver package
6. Create models
Hereby the some sample models, you can see full models in source codes.
7. Add connection string in appsettings.json
Connection string format:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]
If we use the default port then we can skip it in the connection string. You can check more detail here
8. Create database context
9. Add the repository
10. Use DI model to access ContentRepository in ConfigureServices (in Startup.cs)
services.AddTransient();
That’s it! We can access to both types of databases now. However, you have to wait for next parts to see what are the proper ways to use data access in KCommerce project.
You can download the full source codes in Github
Part 5: CQRS and Event Sourcing