首页 > 解决方案 > DDD 中的类别聚合根

问题描述

我需要DDD中的类别聚合根。你能告诉我一个示例代码吗?我的旧域代码:

public class Category{

          public int Id { get; set; }
          public string Name { get; set; }
          public int ParentId{ get; set; }
}

编辑:

我有一个想要转换为 DDD 的旧项目。我在 Category 表与其自身之间的关系中存在问题。

我写了这段代码。但是在AddParentCategory中,我无法检查该类别是否有重复的子类别?我建立的关系对吗?

public class Category : AggregateRoot
{
    public static Result<Category> Create(Category parentCategory, string name)
    {
        var result = new Result<Category>();


        var nameResult = Name.Create(value: name);

        result.WithErrors(errors: nameResult.Errors);

        if (result.IsFailed)
        {
            return result;
        }

        var returnValue = new Category(name: nameResult.Value, parentCategory: parentCategory);

        result.WithValue(value: returnValue);

        return result;
    }

    private Category() : base()
    {
        _products = new();
    }

    private Category(Name name, Category parentCategory) : this()
    {
        Name = name;
        ParentCategory = parentCategory;
    }

    public Name Name { get; private set; }
    public virtual Category ParentCategory { get; private set; }



    public Result<Category> AddParentCategory(string categoryName)
    {
        var result = new Result<Category>();
        var hasAny = this.ParentCategory.Name.Value.ToLower() == categoryName.ToLower();

        if (hasAny)
        {
            string errorMessage = string.Format(Validations.Repetitive, DataDictionary.CityName);

            result.WithError(errorMessage: errorMessage);

            return result;
        }

        result = Category.Create(parentCategory: this, name: categoryName);

        if (result.IsFailed)
        {
            return result.ToResult();
        }

        return result.ToResult();
    }
}

标签: c#asp.netasp.net-coredomain-driven-designaggregateroot

解决方案


推荐阅读