c# - 验证域实体中的唯一值

标签 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;
        }
    }
}

由于我使用的是领域驱动设计,因此产品实体不了解持久性或服务层。我可以按如下方式向服务方法添加检查:

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;
    }

}

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

是否有针对此类场景的最佳实践或已知设计模式?

最佳答案

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

关于c# - 验证域实体中的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915833/

相关文章:

android - 多个 Activity/Fragments 和 Model View Presenter 模式

uml - 在领域模型中使用多重继承是否可以接受?

c# - 在 C# 中实现 DDD 实体类

c# - 多分辨率图像在 WP8 中无法正确渲染

c# - 接口(interface)实现理念

c# - 自动查看哪些函数可能在 C# 中返回异常的方法

java - 为对象组合选择正确的模式

java - 在自定义 View 的点击监听器上实现可重用的自定义

rest - DDD 模型和 Rest API

c# - Execute Scalar、Execute Reader 和 Data Set 在哪里使用?