Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use .NET 6 to develop TodoList applications and introduce data Storage

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use .NET 6 to develop TodoList applications to introduce data storage", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use .NET 6 to develop TodoList applications and introduce data storage.

Demand

As a back-end CRUD programmer (bushi), data storage is a very important component for developing back-end services. Naturally, for our TodoList project, we also need to configure the data store. The current demand is simple:

Need to be able to persist and manipulate TodoList objects

Need to be able to persist and manipulate TodoItem objects

The question is, how are we going to store the data?

There are many choices for storage components: relational databases represented by MSSQL Server/Postgres/MySql/SQLite, non-relational databases represented by MongoDB/ElasticSearch, etc., in addition, we can also choose in-memory databases during the development phase and similar to Azure Cosmos DB/AWS DynamoDB and a variety of relational databases provided on the cloud when deploying on the cloud.

Applications use database services, generally with the help of mature third-party ORM frameworks, while in the .NET back-end service development process, the two most used ORM frameworks should be: EntityFrameworkCore and Dapper, in contrast, the utilization rate of EFCore is higher. So we also chose EFCore to demonstrate.

target

In this article, we only discuss how to implement the introduction of a data storage infrastructure, which is specifically discussed later in the definition and operation of specific entities.

Use the MSSQL Server container as the data storage component (if you need to install the Docker environment on your computer, download and install Docker Desktop)

The reason for this choice is also simple. For partners using Mac, using containers to launch MSSQL Server can avoid problems that the examples cannot run because of non-Windows platforms.

Principles and ideas

Because there are differences in the configuration of the development environment and the production environment, let's take a look at the common parts:

Introduce EFCore-related nuget packages and configure them

Add DbContext objects and do dependency injection

Modify the related appsettings. {environment} .json file

Main program configuration.

Run the MSSQL Server container locally and persist the data

As in the previous article, we put the logic of interfacing with specific third parties into Infrastructure, and only abstract operations on external services are retained in the application.

Achieve 1. Introduce and configure the Nuget package

The following Nuget packages need to be introduced into the Infrastructure project:

The second package of Microsoft.EntityFrameworkCore.SqlServer# is needed to use the PowerShell command (Add-Migration/Update-Database/...), and if you use eftool, you don't have to install this package. Microsoft.EntityFrameworkCore.Tools

In order to use eftool, the following Nuget packages need to be introduced into the Api project:

Microsoft.EntityFrameworkCore.Design2. Add DBContext objects and configure them

In this step, we are going to add a specific DBContext object, which is not a difficult task for experienced developers. But before we implement it, we can take a moment to think about the current Clean Architecture structure: our goal is to shield the underlying implementation in both Application and Domain, in addition to Infrastructure knowing what the third party of the specific interaction is. In other words, we need to use interfaces in projects other than Infrastrcuture to abstract the concrete implementation, so we create a new Common/Interfaces folder in Application to hold the abstract interface IApplicationDbContext defined by the application:

Namespace TodoList.Application.Common.Interfaces;public interface IApplicationDbContext {Task SaveChangesAsync (CancellationToken cancellationToken);}

Next, create a new Persistence folder in the Infrastructure project to hold the specific logic related to data persistence, where we define the DbContext object and implement the interface just defined.

Using Microsoft.EntityFrameworkCore;using TodoList.Application.Common.Interfaces;namespace TodoList.Infrastructure.Persistence;public class TodoListDbContext: DbContext, IApplicationDbContext {public TodoListDbContext (DbContextOptions options): base (options) {}}

The way it is handled here may cause confusion about the meaning of this IApplicationDbContext. The question here is related to whether or not to use the Repository model, which has been discussed by many foreign bigwigs, that is, whether Repository is necessary. You can simply understand that the consensus reached is: it is not necessary, if there is not some special database access logic, or there is a good reason to use the Repository schema, then keep the architecture simple and directly inject the IApplicationDbContext into multiple CQRS Handlers in the Application layer to access the database and operate. If you need to use the Repository schema, there is no need to define this interface to use here. You only need to define IRepository in Application and access DbContext in the BaseRepository implemented in Infrastructure.

We need to use Repository later because we want to demonstrate the most commonly used development patterns, but the reason I keep IApplicationDbConetxt in this article is that I also want to show a different implementation style, and we will focus on Repository later.

Once the required objects are added, the next step is to configure DbContext. Let's follow the current architectural style and add the DependencyInjection.cs file in the Infrastructure project to add all third-party dependencies:

Using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using TodoList.Application.Common.Interfaces;using TodoList.Infrastructure.Persistence;namespace TodoList.Infrastructure;public static class DependencyInjection {public static IServiceCollection AddInfrastructure (this IServiceCollection services, IConfiguration configuration) {services.AddDbContext (options = > options.UseSqlServer (configuration.GetConnectionString ("SqlServerConnection"), b = > b.MigrationsAssembly (typeof (TodoListDbContext) .Assembly.FullName) Services.AddScoped (provider = > provider.GetRequiredService ()); return services;} 3. Profile modification

We configure the appsettings.Development.json file:

{"Logging": {"LogLevel": {"Default": "Information", "Microsoft.AspNetCore": "Warning"}, "UseFileToLog": true, "ConnectionStrings": {"SqlServerConnection": "Server=localhost,1433;Database=TodoListDb;User Id=sa;Password=StrongPwd123;"}}

It should be noted here that if you are using MSSQL Server default port 1433, you can not write it in the connection string, but in order to show how to configure the default port if you are not using it, it is explicitly written here for your reference.

4. Main program configuration

In the Api project, we only need to call the extension method written above to complete the configuration.

Var builder = WebApplication.CreateBuilder (args); / / Add services to the container.builder.ConfigureLog (); builder.Services.AddControllers (); builder.Services.AddEndpointsApiExplorer (); builder.Services.AddSwaggerGen (); / / add infrastructure configuration builder.Services.AddInfrastructure (builder.Configuration); / / omit the following. 5. Running MSSQL Server containers locally and data persistence

After ensuring that the local Docker environment starts properly, run the following command:

# pull mssql image $docker pull mcr.microsoft.com/mssql/server:2019-latest2019-latest: Pulling from mssql/server7b1a6ab2e44d: Already exists 4ffe416cf537: Pull complete fff1d174f64f: Pull complete 3588fd79aff7: Pull complete c8203457909f: Pull complete Digest: sha256:a098c9ff6fbb8e1c9608ad7511fa42dba8d22e0d50b48302761717840ccc26afStatus: Downloaded newer image for mcr.microsoft.com/mssql/server:2019-latestmcr.microsoft.com/mssql/server:2019-latest# create persistent storage $docker create-v / var/opt/mssql-- name mssqldata mcr.microsoft.com/mssql/server:2019 -latest / bin/true3c144419db7fba26398aa45f77891b00a3253c23e9a1d03e193a3cf523c66ce1# runs the mssql container Mount persistent storage volume $docker run-d-- volumes-from mssqldata-- name mssql-e 'ACCEPT_EULA=Y'-e' SA_PASSWORD=StrongPwd123'-p 1433 ACCEPT_EULA=Y' 1433 mcr.microsoft.com/mssql/server:2019-latestd99d774f70229f688d71fd13e90165f15abc492aacec48de287d348e047a055e# confirm container running status $docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESd99d774f7022 mcr.microsoft.com/mssql/server:2019-latest "/ opt/mssql/bin/perm..." 24 seconds ago Up 22 seconds 0.0.0.01433/tcp mssql 1433-> 1433/tcp mssql authentication

In order to verify whether we can successfully connect to the database, we add Migration and Migration the database automatically when the program starts:

First install the tools:

Dotnet tool install-- global dotnet-ef# dotnet tool update-- global dotnet-ef# generates Migration$ dotnet ef migrations add SetupDb-p src/TodoList.Infrastructure/TodoList.Infrastructure.csproj-s src/TodoList.Api/TodoList.Api.csprojBuild started...Build succeeded. [17:29:15 INF] EntityFrameworkCore 6.0.1 initialized 'TodoListDbContext' using provider' Microsoft.EntityFrameworkCore.SqlServer:6.0.1' with options: MigrationsAssembly=TodoList.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Done. To undo this action, use'ef migrations remove'

In order to automatically Migration when the program starts, we add a file ApplicationStartupExtensions.cs to the Infrastructure project and implement the extension method:

Using Microsoft.AspNetCore.Builder;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.DependencyInjection;using TodoList.Infrastructure.Persistence;namespace TodoList.Infrastructure;public static class ApplicationStartupExtensions {public static void MigrateDatabase (this WebApplication app) {using var scope = app.Services.CreateScope (); var services = scope.ServiceProvider; try {var context = services.GetRequiredService (); context.Database.Migrate () } catch (Exception ex) {throw new Exception ($"An error occurred migrating the DB: {ex.Message}");}

And call the extension method in the Program.cs of the Api project:

/ / omit the above... app.MapControllers (); / / call the extension method app.MigrateDatabase (); app.Run ()

Finally, run the main program:

$dotnet run-- project src/TodoList.ApiBuilding... [17:32:32 INF] EntityFrameworkCore 6.0.1 initialized 'TodoListDbContext' using provider' Microsoft.EntityFrameworkCore.SqlServer:6.0.1' with options: MigrationsAssembly=TodoList.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null [17:32:32 INF] Executed DbCommand (22ms) [Parameters= [], CommandType='Text', CommandTimeout='30'] SELECT 1 [17:32:32 INF] Executed DbCommand (19ms) [Parameters= [], CommandType='Text' CommandTimeout='30'] SELECT OBJECT_ID (N' [_ EFMigrationsHistory]') [17:32:32 INF] Executed DbCommand (3ms) [Parameters= [], CommandType='Text', CommandTimeout='30'] SELECT 1 [17:32:32 INF] Executed DbCommand (2ms) [Parameters= [], CommandType='Text', CommandTimeout='30'] SELECT OBJECT_ID (N' [_ EFMigrationsHistory]'); [17:32:33 INF] Executed DbCommand (4ms) [Parameters= [], CommandType='Text', CommandTimeout='30'] SELECT [MigrationId], [ProductVersion] FROM [_ EFMigrationsHistory] ORDER BY [MigrationId] [17:32:33 INF] Applying migration '20211220092915 SetupDbaths. [17:32:33 INF] Executed DbCommand (4ms) [Parameters= [], CommandType='Text', CommandTimeout='30'] INSERT INTO [_ EFMigrationsHistory] ([MigrationId], [ProductVersion]) VALUES (Numbai 20211220092915 SetupDbins, Nobles 6.0.1'); [17:32:33 INF] Now listening on: https://localhost:7039[17:32:33 INF] Now listening on: http://localhost:5050[17:32:33 INF] Application started. Press Ctrl+C to shut down. [17:32:33 INF] Hosting environment: Development [17:32:33 INF] Content root path: / Users/yu.li1/Projects/asinta/blogs/cnblogs/TodoList/src/TodoList.Api/

Using the database tool to connect to the container database, you can see that Migration has successfully written to the database table _ _ EFMigrationsHistory:

At this point, I believe you have a deeper understanding of "how to use .NET 6 to develop TodoList applications to introduce data storage". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report