如果 PurchaseLog 不是它自己的聚合,则意味着它只能作为 SnackMachine 的子集合的一部分进行检索或添加。
因此,每次您想要添加 PurchaseLog 时,您都需要检索 SnackMachine 及其子 PurchaseLogs,然后将 PurchaseLog 添加到它的集合中。然后保存对工作单元的更改。
您真的需要检索 30 多条多余的购买日志,以用于创建新购买日志的用例吗?
应用层 - 选项 1(PurchaseLog 是 SnackMachine 的拥有实体)
// Retrieve the snack machine from repo, along with child purchase logs
// Assuming 30 logs, this would retrieve 31 entities from the database that
// your unit of work will start tracking.
SnackMachine snackMachine = await _snackMachineRepository.GetByIdAsync(snackMachineId);
// Ask snack machine to add a new purchase log to its collection
snackMachine.AddPurchaseLog(date, quantity);
// Update
await _unitOfWork.SaveChangesAsync();
应用层 - 选项 2(PurchaseLog 是聚合根)
// Get a snackmachine from the repo to make sure that one exists
// for the provided id. (Only 1 entity retrieved);
SnackMachine snackMachine = await _snackMachineRepository.GetByIdAsync(snackMachineId);
// Create Purhcase log
PurchaseLog purchaseLog = new(
snackMachine,
date,
quantity);
await _purchaseLogRepository.AddAsync(purchaseLog);
await _unitOfWork.SaveChangesAsync()
PurchaseLog - 选项 2
class PurchaseLog
{
int _snackMachineId;
DateTimne _date;
int _quantity;
PurchaseLog(
SnackMachine snackMachine,
DateTime date,
int quantity)
{
_snackMachineId = snackMachine?.Id ?? throw new ArgumentNullException(nameof(snackMachine));
_date = date;
_quantity = quantity;
}
}
第二个选项更准确地遵循您的用例的轮廓,同时也减少了数据库的 I/O。