I have come from a transaction script world and I am just starting to take a look at DDD. I am unsure of the correct way to integrate a DDD design with database persistence. This is what I have:
A service class called OrganisationService whose interface contains methods for retrieving and saving away instances of Organisation domain objects. Organisation is an aggregate root and has other data related to it: Members and Licenses. EF6 database first DBContext is used within the OrganisationService to retrieve OrganisationDB entities and the related MemberDB and LicenseDB entities. These all get transformed into their domain object class equivalents when retrieved by the OrganisationService and loaded into the Organisation domain object. This object looks like so:
public class Organisation
{
public IList<Member> Members { get; set; }
public IList<License> Licenses { get; set; }
}
I am not using the Repository pattern in the OrganisationService...I am using EF itself as the Repository as it seems that EF6 has largely made repository redundant now.
At this point in the design the Organisation domain object is anaemic: it looks like the EF POCO Organisation class. The OrganisationService class looks a lot like a Repository!
Now I need to start adding logic. This logic includes managing an Organisations Licenses and Members. Now in the transaction script days I would add methods into the OrganisationService for handling these operations and call into a Repository to interact with the DB, but with DDD I believe this logic should be encapsulated within the Organisation domain object itself...
This is where I am unsure of what I should be doing: I will need to persist this data back to the database as part of the logic. Does this mean I should use DbContext within the Organisation domain object to do this? Is using the repository/EF within the domain object bad practice? If so, where does this persistence belong?
public class Organisation
{
public IList<Member> Members { get; set; }
public IList<License> Licenses { get; set; }
public void AddLicensesToOrganisation(IList<License> licensesToAdd)
{
// Do validation/other stuff/
// And now Save to the DB???
using(var context = new EFContext())
{
context.Licenses.Add(...
}
// Add to the Licenses collection in Memory
Licenses.AddRange(licensesToAdd);
}
}
Should I instead just be mutating the Organisation domain object in memory and then pushing it back to the OrganisationService for persistence? Then I have to track what actually changed on the object (which is what EF does to its own POCOs! I am kind of coming to feel that EF isn't just a repository replacement, but also could be the domain layer!)
Any guidance here is appreciated.