Search code examples
c#entity-framework-coredomain-driven-designaggregates

Get child data by child id through the aggregate root in DDD and EF Core


For asking my question let me explain a bit about this part of the project:
Very simple blog system with these entities:
Posts - PostsCategories - Categories
Post and Category have Many-to-Many relationships.

// Post
public Id { get; private set; }
public Title { get; private set; }
public IReadOnlyCollection<PostsCategories> Categories => _categories;
private List<PostsCategories> _categories = new();
// Category
public Id { get; private set; }
public Title { get; private set; }
public IReadOnlyCollection<PostsCategories> Posts => _posts;
private List<PostsCategories> _posts = new();
// PostsCategories (this is Value Object)
public Guid PostId { get; private set; }
public Post Post { get; protected set; }

public Guid CategoryId { get; private set; }
public Category Category { get; protected set; }

These 3 entities are in Blog aggregate: Post is Aggregate root, Category is entity, and PostsCategories is ValueObject.
Now as I know (In DDD we should have one repository for each AggregateRoot and other members can not have repository) So I want to get category by id with EF Core.

This is my question: How can I get single category with its posts with having category Id in the PostsRepository.cs?

============== Update ===============
Is this query correct? (Performance and standards)

var category = await Entity
.Include(x => x.Categories)
.ThenInclude(x => x.Category)SelectMany(x => x.Categories)
.Select(x => x.Category)
.FirstOrDefaultAsync(x => string.Equals(x.Slug.Value, slug, StringComparison.OrdinalIgnoreCase));

Solution

  • After researching and reading about this topic, I found out that I had a miss understanding of aggregation, in the case if, I was putting Categories in another aggregate called Blog or Post that Post is an Aggregate root, So how about if I needed to get the list of all categories? with DDD and my implementation, I could not do that! because I can only access to categories that they are assigned to post! This is a sign to transfer the Category entity to another aggregate.