258
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Figure 7-19. Azure Cosmos DB global distribution
When you use a C# model to implement the aggregate to be used by the Azure Cosmos DB API, the
aggregate can be similar to the C# POCO classes used with EF Core. The difference is in the way to
use them from the application and
infrastructure layers, as in the following code:
// C# EXAMPLE OF AN ORDER AGGREGATE BEING PERSISTED WITH AZURE COSMOS DB API
// *** Domain Model Code ***
// Aggregate: Create an Order object with its child entities and/or value objects.
// Then, use AggregateRoot's methods to add the nested objects so invariants and
// logic is consistent across the nested properties (value objects and entities).
Order orderAggregate =
new
Order
{
Id =
"2024001"
,
OrderDate =
new
DateTime
(
2005
,
7
,
1
),
BuyerId =
"1234567"
,
PurchaseOrderNumber =
"PO18009186470"
}
Address address =
new
Address
{
Street =
"100 One Microsoft Way"
,
City =
"Redmond"
,
State =
"WA"
,
Zip =
"98052"
,
Country =
"U.S."
}
orderAggregate.
UpdateAddress
(address);
OrderItem orderItem1 =
new
OrderItem
{
259
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Id =
20240011
,
ProductId =
"123456"
,
ProductName =
".NET T-Shirt"
,
UnitPrice =
25
,
Units =
2
,
Discount =
0
;
};
//Using methods with domain logic within the entity. No anemic-domain model
orderAggregate.
AddOrderItem
(orderItem1);
// *** End of Domain Model Code ***
// *** Infrastructure Code using Cosmos DB Client API ***
Uri collectionUri = UriFactory.
CreateDocumentCollectionUri
(databaseName,
collectionName);
await client.
CreateDocumentAsync
(collectionUri, orderAggregate);
// As your app evolves, let's say your object has a new schema. You can insert
// OrderV2 objects without any changes to the database tier.
Order2 newOrder =
GetOrderV2Sample
(
"IdForSalesOrder2"
);
await client.
CreateDocumentAsync
(collectionUri, newOrder);
You can see that the way you work with your domain model can be similar to the way you use it in
your domain model layer when the infrastructure is EF. You still use the same aggregate root
methods
to ensure consistency, invariants, and validations within the aggregate.
However, when you persist your model
into the NoSQL database, the code and API change
dramatically compared to EF Core code or any other code related to relational databases.
Dostları ilə paylaş: