验证域实体中的唯一值

Bra*_*ite 1 c# design-patterns domain-driven-design

我有一个场景,需要验证域实体属性的唯一性,然后才能将其保存到数据库。这是一个简单的Product类。假设我想验证在创建新产品时ProductKey 字符串属性是唯一的

public class Product : EntityBase
{
    int ID { get; set; }
    string ProductKey { get; set; }
    int CategoryID { get; set; }

    bool IsValid
    {
        get
        {
            if (string.IsNullOrEmpty(ProductKey))
            {
                ValidationErrors.Add("ProductKey Required.");
            }

            if (CategoryID == 0)
            {
                ValidationErrors.Add("CategoryID Required.");
            }

            /* Validation that the product key is unique could go here? i.e. requires a database read. */

            return ValidationErrors.Count() == 0;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

由于我使用领域驱动设计,产品实体不了解持久性或服务层。我可以向 Service 方法添加一个检查,如下所示:

public class ProductService 
{
    private IProductRepository _productRepository = new ProductRepository();

    public int CreateProduct(Product item) 
    {
        if (item.IsValid)
        {
            if (ProductKeyIsUnique(item.ProductKey))
            {
                _productRepository.Add(item);
            }
            else
            {
                throw new DuplicateProductKeyException();
            }

        }
    }

    private bool ProductKeyIsUnique(string productKey)
    {
        return _productRepository.GetByKey(productKey) == null;
    }

}
Run Code Online (Sandbox Code Playgroud)

这很简单,但理想情况下我希望这样的逻辑存在于领域模型中。也许通过引发某种可以被服务层捕获的验证事件?

对于这种类型的场景是否有最佳实践或已知的设计模式?

mas*_*ted 5

产品密钥唯一性不是领域对象知识。因此您不需要对其进行域验证。为什么产品应该关心关键的唯一性?在我看来,这是应用程序层的责任。您的解决方案似乎有效并且适合我。