使用.NET?6開發(fā)TodoList應(yīng)用之引入數(shù)據(jù)存儲的思路詳解
需求
作為后端CRUD程序員(bushi,數(shù)據(jù)存儲是開發(fā)后端服務(wù)一個非常重要的組件。對我們的TodoList項目來說,自然也需要配置數(shù)據(jù)存儲。目前的需求很簡單:
- 需要能持久化
TodoList對象并對其進行操作; - 需要能持久化
TodoItem對象并對其進行操作;
問題是,我們打算如何存儲數(shù)據(jù)?
存儲組件的選擇非常多:以MSSQL Server/Postgres/MySql/SQLite等為代表的關(guān)系型數(shù)據(jù)庫,以MongoDB/ElasticSearch等為代表的非關(guān)系型數(shù)據(jù)庫,除此之外,我們還可以在開發(fā)階段選擇內(nèi)存數(shù)據(jù)庫,在云上部署的時候還可以選擇類似Azure Cosmos DB/AWS DynamoDB以及云上提供的多種關(guān)系型數(shù)據(jù)庫。
應(yīng)用程序使用數(shù)據(jù)庫服務(wù),一般都是借助成熟的第三方ORM框架,而在.NET后端服務(wù)開發(fā)的過程中,使用的最多的兩個ORM框架應(yīng)該是:EntityFrameworkCore和Dapper,相比之下,EFCore的使用率更高一些。所以我們也選擇EFCore來進行演示。
目標(biāo)
在這篇文章中,我們僅討論如何實現(xiàn)數(shù)據(jù)存儲基礎(chǔ)設(shè)施的引入,具體的實體定義和操作后面專門來說。
- 使用MSSQL Server容器作為數(shù)據(jù)存儲組件(前提是電腦上需要安裝Docker環(huán)境,下載并安裝Docker Desktop即可);
這樣選擇的理由也很簡單,對于使用Mac的小伙伴來說,使用容器來啟動MSSQL Server可以避免因為非Windows平臺導(dǎo)致的示例無法運行的問題。
原理和思路
因為我們對開發(fā)環(huán)境和生產(chǎn)環(huán)境的配置有差異,那先來看看共性的部分:
- 引入EFCore相關(guān)的nuget包并進行配置;
- 添加DbContext對象并進行依賴注入;
- 修改相關(guān)appsettings.{environment}.json文件;
- 主程序配置。
- 本地運行MSSQL Server容器并實現(xiàn)數(shù)據(jù)持久化;
同上一篇一樣,和具體的第三方對接的邏輯我們還是放到Infrastructure里面去,應(yīng)用程序中只保留對外部服務(wù)的抽象操作。
實現(xiàn)
1. 引入Nuget包并進行配置
需要在Infrastructure項目中引入以下Nuget包:
Microsoft.EntityFrameworkCore.SqlServer # 第二個包是用于使用PowerShell命令(Add-Migration/Update-Database/...)需要的,如果使用eftool,可以不安裝這個包。 Microsoft.EntityFrameworkCore.Tools
為了使用eftool,需要在Api項目中引入以下Nuget包:
Microsoft.EntityFrameworkCore.Design
2. 添加DBContext對象并進行配置
在這一步里,我們要添加的是一個具體的DBContext對象,這對于有經(jīng)驗的開發(fā)者來說并不是很難的任務(wù)。但是在具體實現(xiàn)之前,我們可以花一點時間考慮一下現(xiàn)在的Clean Architecture結(jié)構(gòu):我們的目的是希望除了Infrastructure知道具體交互的第三方是什么,在Application以及Domain里都要屏蔽底層的具體實現(xiàn)。換言之就是需要在Infrastrcuture之外的項目中使用接口來做具體實現(xiàn)的抽象,那么我們在Application中新建一個Common/Interfaces文件夾用于存放應(yīng)用程序定義的抽象接口IApplicationDbContext:
namespace TodoList.Application.Common.Interfaces;
public interface IApplicationDbContext
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
接下來在Infrastructure項目中新建Persistence文件夾用來存放和數(shù)據(jù)持久化相關(guān)的具體邏輯,我們在其中定義DbContext對象并實現(xiàn)剛才定義的接口。
using Microsoft.EntityFrameworkCore;
using TodoList.Application.Common.Interfaces;
namespace TodoList.Infrastructure.Persistence;
public class TodoListDbContext : DbContext, IApplicationDbContext
{
public TodoListDbContext(DbContextOptions<TodoListDbContext> options) : base(options)
{
}
}
這里的處理方式可能會引起困惑,這個IApplicationDbContext存在的意義是什么。這里的疑問和關(guān)于要不要使用Repository模式有關(guān),國外多位大佬討論過這個問題,即Repository是不是必須的??梢院唵卫斫獯蠹疫_成的共識是:不是必須的,如果不是有某些特別的數(shù)據(jù)庫訪問邏輯,或者有足夠的理由需要使用Repository模式,那就保持架構(gòu)上的簡潔,在Application層的多個CQRS Handlers中直接注入該IApplicationDbContext去訪問數(shù)據(jù)庫并進行操作。如果需要使用Repository模式,那在這里就沒有必要定義這個接口來使用了,Application中只需要定義IRepository<T>,在Infrastructure中實現(xiàn)的BaseRepository中訪問DbContext即可。
我們后面是需要使用Repository的,是因為希望演示最常用的開發(fā)模式,但是在這一篇中我保留IApplicationDbConetxt的原因是也希望展示一種不同的實現(xiàn)風(fēng)格,后面我們還是會專注到Repository上的。
需要的對象添加好了,下一步是配置DbContext,我們還是遵循當(dāng)前的架構(gòu)風(fēng)格,在Infrastructure項目中添加DependencyInjection.cs文件用于添加所有第三方的依賴:
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<TodoListDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("SqlServerConnection"),
b => b.MigrationsAssembly(typeof(TodoListDbContext).Assembly.FullName)));
services.AddScoped<IApplicationDbContext>(provider => provider.GetRequiredService<TodoListDbContext>());
return services;
}
}
3. 配置文件修改
我們對appsettings.Development.json文件進行配置:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"UseFileToLog": true,
"ConnectionStrings": {
"SqlServerConnection": "Server=localhost,1433;Database=TodoListDb;User Id=sa;Password=StrongPwd123;"
}
}
這里需要說明的是如果是使用MSSQL Server默認(rèn)端口1433的話,連接字符串里是可以不寫的,但是為了展示如果使用的不是默認(rèn)端口應(yīng)該如何配置,還是顯式寫在這里了供大家參考。
4. 主程序配置
在Api項目中,我們只需要調(diào)用上面寫好的擴展方法,就可以完成配置。
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.ConfigureLog(); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); // 添加基礎(chǔ)設(shè)施配置 builder.Services.AddInfrastructure(builder.Configuration); // 省略以下...
5. 本地運行MSSQL Server容器及數(shù)據(jù)持久化
在保證本地Docker環(huán)境正常啟動之后,運行以下命令:
# 拉取mssql鏡像 $ docker pull mcr.microsoft.com/mssql/server:2019-latest 2019-latest: Pulling from mssql/server 7b1a6ab2e44d: Already exists 4ffe416cf537: Pull complete fff1d174f64f: Pull complete 3588fd79aff7: Pull complete c8203457909f: Pull complete Digest: sha256:a098c9ff6fbb8e1c9608ad7511fa42dba8d22e0d50b48302761717840ccc26af Status: Downloaded newer image for mcr.microsoft.com/mssql/server:2019-latest mcr.microsoft.com/mssql/server:2019-latest # 創(chuàng)建持久化存儲 $ docker create -v /var/opt/mssql --name mssqldata mcr.microsoft.com/mssql/server:2019-latest /bin/true 3c144419db7fba26398aa45f77891b00a3253c23e9a1d03e193a3cf523c66ce1 # 運行mssql容器,掛載持久化存儲卷 $ docker run -d --volumes-from mssqldata --name mssql -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=StrongPwd123' -p 1433:1433 mcr.microsoft.com/mssql/server:2019-latest d99d774f70229f688d71fd13e90165f15abc492aacec48de287d348e047a055e # 確認(rèn)容器運行狀態(tài) $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d99d774f7022 mcr.microsoft.com/mssql/server:2019-latest "/opt/mssql/bin/perm…" 24 seconds ago Up 22 seconds 0.0.0.0:1433->1433/tcp mssql
驗證
為了驗證我們是否可以順利連接到數(shù)據(jù)庫,我們采用添加Migration并在程序啟動時自動進行數(shù)據(jù)庫的Migration方式進行:
首先安裝工具:
dotnet tool install --global dotnet-ef # dotnet tool update --global dotnet-ef # 生成Migration $ dotnet ef migrations add SetupDb -p src/TodoList.Infrastructure/TodoList.Infrastructure.csproj -s src/TodoList.Api/TodoList.Api.csproj Build started... Build succeeded. [17:29:15 INF] Entity Framework Core 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'
為了在程序啟動時進行自動Migration,我們向Infrastructure項目中增加一個文件ApplicationStartupExtensions.cs并實現(xiàn)擴展方法:
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<TodoListDbContext>();
context.Database.Migrate();
}
catch (Exception ex)
{
throw new Exception($"An error occurred migrating the DB: {ex.Message}");
}
}
}
并在Api項目的Program.cs中調(diào)用擴展方法:
// 省略以上... app.MapControllers(); // 調(diào)用擴展方法 app.MigrateDatabase(); app.Run();
最后運行主程序:
$ dotnet run --project src/TodoList.Api Building... [17:32:32 INF] Entity Framework Core 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_SetupDb'. [17:32:33 INF] Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion]) VALUES (N'20211220092915_SetupDb', N'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/
使用數(shù)據(jù)庫工具連接容器數(shù)據(jù)庫,可以看到Migration已經(jīng)成功地寫入數(shù)據(jù)庫表__EFMigrationsHistory了:

本篇文章僅完成了數(shù)據(jù)存儲服務(wù)的配置工作,目前還沒有添加任何實體對象和數(shù)據(jù)庫表定義,所以暫時沒有可視化的驗證,僅我們可以運行程序看我們的配置是否成功:
總結(jié)
在本文中,我們探討并實現(xiàn)了如何給.NET 6 Web API項目添加數(shù)據(jù)存儲服務(wù)并進行配置,下一篇開始將會深入數(shù)據(jù)存儲部分,定義實體,構(gòu)建Repository模式和SeedData等操作。
除了本文演示的最基礎(chǔ)的使用方式意外,在實際使用的過程中,我們可能會遇到類似:為多個DbContext分別生成Migrations或者為同一個DbContext根據(jù)不同的環(huán)境生成不同Database Provider適用的Migrations等情況,擴展閱讀如下,在這里就不做進一步的演示了,也許以后有機會可以單獨寫篇實踐指南:
參考資料
到此這篇關(guān)于使用.NET 6開發(fā)TodoList應(yīng)用之引入數(shù)據(jù)存儲的文章就介紹到這了,更多相關(guān).NET 6開發(fā)TodoList引入數(shù)據(jù)存儲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- .NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)查詢分頁
- .NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)ActionFilter
- .NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)接口請求驗證
- .NET?6開發(fā)TodoList應(yīng)用之實現(xiàn)DELETE請求與HTTP請求冪等性
- .NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)PUT請求
- .NET 6開發(fā)TodoList應(yīng)用之實現(xiàn)全局異常處理
- .NET 6開發(fā)TodoList應(yīng)用之使用AutoMapper實現(xiàn)GET請求
- .NET?6開發(fā)TodoList應(yīng)用之實現(xiàn)Repository模式
- .NET?6開發(fā)TodoList應(yīng)用之使用MediatR實現(xiàn)POST請求
- .NET 6開發(fā)TodoList應(yīng)用引入數(shù)據(jù)存儲
- .NET?6開發(fā)TodoList應(yīng)用引入第三方日志庫
- .NET 6開發(fā)TodoList應(yīng)用實現(xiàn)結(jié)構(gòu)搭建
- .NET?6開發(fā)TodoList應(yīng)用實現(xiàn)系列背景
- 使用.NET?6開發(fā)TodoList應(yīng)用之領(lǐng)域?qū)嶓w創(chuàng)建原理和思路
- .NET?6開發(fā)TodoList應(yīng)用之請求日志組件HttpLogging介紹
相關(guān)文章
MVC使用極驗驗證制作登錄驗證碼學(xué)習(xí)筆記7
這篇文章主要介紹了MVC使用極驗驗證制作登錄驗證碼學(xué)習(xí)筆記,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09
詳解Asp.net web.config customErrors 如何設(shè)置
這篇文章主要介紹了詳解Asp.net web.config customErrors 如何設(shè)置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
asp.net 抓取網(wǎng)頁源碼三種實現(xiàn)方法
asp.net 抓取網(wǎng)頁源碼三種實現(xiàn)方法,需要的朋友可以參考一下2013-06-06
Asp.net中斷點續(xù)傳的原理與實現(xiàn)方法分享
在了解HTTP斷點續(xù)傳的原理之前,讓我們先來了解一下HTTP協(xié)議,HTTP協(xié)議是一種基于tcp的簡單協(xié)議,分為請求和回復(fù)兩種2012-08-08
.net全局定時定期執(zhí)行某些操作在Global.asax中具體實現(xiàn)
全局定時定期執(zhí)行某些操作看起來是多么自動化的一個問題不過在.net的Global.asax文件中稍微配置即可實現(xiàn),詳細(xì)配置如下,感興趣的朋友可以參考下哈2013-04-04

