我是 DDD 概念的新手,在从持久层重建我的域模型时遇到了一些问题,即如何处理由于业务规则而通常不允许的对象创建。
例如,Invoice 和 InvoiceRows 的概念。将发票发送给客户后,业务规则不允许将发票行添加到发票中。
我的域模型看起来像这样:
class Invoice
{
List<InvoiceRow> _rows = new List<InvoiceRow>();
public bool IsSent { get; private set; }
Invoice(bool isSent)
{
this.IsSent = isSent;
}
public InvoiceRow AddRow(Product product, decimal amount)
{
if (IsSent) throw new InvalidOperationException("Invoice already sent to customer.");
var row = new InvoiceRow(this, product, amount);
_rows.Add(row);
return row;
}
public void Send(object service)
{
if (IsSent) throw new InvoiceAlreadySentException();
service.SendInvoice(this);
this.IsSent = true;
}
}
class InvoiceRow
{
public Product Product { get; private set; }
public decimal Amount { get; private set; }
public Invoice Invoice { get; private set; }
InvoiceRow(Invoice parent, Product product, decimal amount)
{
this.Invoice = parent;
this.Product = product;
this.Amount = amount;
}
}
在重建包含已发送的数据库中的行的发票模型时,如果已发送发票,则会出现添加发票行被域模型拒绝的问题。
例如:
Invoice invoice = new Invoice(invoiceDto.IsSent);
foreach(row in invoiceRowsDto)
{
invoice.AddRow(row.Product, row.Amount); // Not allowed because the invocie has been sent...
}
当然,可以添加带有行列表的构造函数参数,但这使得可以将相同的行列表添加到不同的发票。
var listOfRows = somelistofinvoicerowsretrievedfromdatabase;
var invoice1 = new Invoice(issent=true, listofrows);
var invoice2 = new Invoice(issent=false, listofrows);
解决此问题的最佳方法是什么?