前言
根據參考網站照著步驟DEMO的CQRS架構
以CQRS Pattern來達成資料庫"讀寫"模組分離的架構
架構圖大致上是長這樣
如果搭配MicroService 和Dapper的話,可以設計成這樣
搭配Dapper讀取資料庫時,如果使用動態型別,可像下面這樣設計
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface IEmployeeQueriesRepository
{
Task<IEnumerable<dynamic>> GetEmployeeAsync1();
}
public class EmployeeQueriesRepository : IEmployeeQueriesRepository
{
public async Task<IEnumerable<dynamic>> GetEmployeeAsync1()
{
using (var connection = new SqlConnection(@"SqlConnection"))
{
string strQUERY = @"
Select
Id as N'Id',
FirstName as N'FirstName',
LastName as N'LastName',
DateOfBirth as N'DateOfBirth',
Street as N'Street',
City as N'City',
ZipCode as N'ZipCode'
from dbo.EmployeeSheet
";
connection.Open();
return await connection.QueryAsync<dynamic>(strQUERY);
}
}
}
搭配Dapper讀取資料庫時,如果有明確型別,可像下面這樣設計
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public interface IEmployeeQueriesRepository
{
Task<IEnumerable<Employee>> GetEmployeeAsync1();
}
public class EmployeeQueriesRepository : IEmployeeQueriesRepository
{
public async Task<IEnumerable<Employee>> GetEmployeeAsync1()
{
using (var connection = new SqlConnection(@"SqlConnection"))
{
string strQUERY = @"
Select
Id as N'Id',
FirstName as N'FirstName',
LastName as N'LastName',
DateOfBirth as N'DateOfBirth',
Street as N'Street',
City as N'City',
ZipCode as N'ZipCode'
from dbo.EmployeeSheet
";
connection.Open();
return await connection.QueryAsync<Employee>(strQUERY);
}
}
}
GitHub
https://github.com/digamana/CQRS-PatternRepo.git
參考
https://learn.microsoft.com/zh-tw/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/cqrs-microservice-reads
https://www.partech.nl/nl/publicaties/2021/05/using-the-cqrs-pattern-in-c-sharp