user2822838
user2822838

Reputation: 347

Deleting entity when a referenced entity is deleted

Using DDD, I have 4 aggregate roots where, using the appointment analogy, a clinic can have a number of patients, each patient can have a number of appointments, each appointment can have a number of prescriptions.

Now, to avoid creating a very big bloated Aggregate, Clinic in this case, I have created 4 separate aggregate roots.

public class Clinic
{
    public Guid Id { get; private set; }
}

public class Patient
{
    public Guid Id { get; private set; }

    public Guid ClinicId { get; private set; }

    public Patient(Guid clinicId)
    {
        ClinicId = clinicId;
    }
}


public class Appointment
{
    public Guid Id { get; private set; }

    public Guid PatientId { get; private set; }

    public Appointment(Guid patientId)
    {
        PatientId = patientId;
    }
}

Now, the question is how should I manage the scenario where a patient is deleted, in which case all appointments referencing this patient should be deleted too.

Upvotes: 2

Views: 126

Answers (1)

Eben Roux
Eben Roux

Reputation: 13256

I guess this is where a domain expert is going to come in handy. From a technical point of view it probably is going to depend on the architecture you decide on.

100% consistency

Here you could use an application service to first delete the patient and then all the appointments linked to that patient.

Eventual consistency

Using messaging you could publish PatientDeletedEvent that would be responded to by some endpoint that would delete the appointments.

However

You probably do not want to be deleting patients in the first place. Even so, your questions about the appointments for, say, setting a patient Inactive may still results in you wanting to delete future appointments.

This is where you would need a domain expert to guide you in creating the correct model and behaviour.

Upvotes: 2

Related Questions