Reputation: 655
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));
Upvotes: 0
Views: 947
Reputation: 655
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.
Upvotes: 0
Reputation: 9
The models that are designed in DDD are usually not a good option for queries, and you should use design or other options for the queries. If your goal is to make changes in the category, aggregate should be loaded and changes should be made from the aggregate side. But if your goal is only to display information, you can create a query repository for the category, which is used only for the query.
Upvotes: 1
Reputation: 1
my suggest is do it in CategoryRepository
context.Category.Query().Include(category => category.PostsCategory).ThenInclude(postsCategory => postsCategory.Post).FirstOrDeafult(category => category.Id == id)
Upvotes: 0