Search code examples
c#.netasp.net-mvcasp.net-coredomain-driven-design

one to many association between two aggregate roots DDD architecture


i develop a project base on DDD architecture with .net core.i have these two aggregate roots

public class Lesson :IAggregateRoot
{
  .......
}

and

public class Question:IAggregateRoot
{
  ............
}

in this domain lessons should have collection of questions so there is one-to-many relationship and this is my question how should i implement it in code?should i save list of question ids in lesson table? thank you


Solution

  • Assuming you have good reason to model both of these as aggregate roots, rather than Lesson being the aggregate root and Questions as child entities, e.g. you have lots of questions and might want to update a question independently of the lesson, then I'd go for:

    public class Lesson : IAggregateRoot
    {
        public int Id { get; set; }
        public string Subject { get; set; }
    
        public Lesson(int id, string subject)
        {
            Id = id;
            Subject = subject;
        }
    }
    

    and

    public class Question : IAggregateRoot
    {
        public int Id { get; set; }
        public int LessonId { get; set; }
        public string Text { get; set; }
    
        public Question(int id, Lesson lesson, string text)
        {
            Id = id;
            LessonId = lesson.Id;
            Text = text;
        }
    }
    

    In this way you can manage the Question's text independently of the Lesson, but are also ensuring that a matching Lesson exists by forcing the application layer to provide a Lesson instance when creating the question.