I currently create a Repository for each database table and a corresponding data class for the column values (object to pass around data).
I recently started using some 1 to 1 relationships and I’m not sure what would be the best way to implement them.
For example
If I have a User table and a UserSettings Table in a 1:1 relationship.
// Data classes (Holds all the field value for the table)
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
}
public class UserSettings
{
public int UserId { get; set; }
public bool SomeSetting { get; set; }
}
Questions:
- Should I always go through the User object to manipulate the UserSettings object, or should I be able to manipulate them
independently? - Should I include the primary key field in the UserSettings object?
-
Should I store a reference to the USerSettings object in the User object?
-
Do I make two repo’s one for User and one UserSettings, or do I handle everything in the Users Repo.
The only time I’ve ever found a 1:1 relationship between aggregate roots to be useful is when the aggregate roots on either side of the relationship are managed by different domains. They must share the same primary key, and therefore if they are both managed by the same domain then they are by definition parts of the same aggregate root. I think you need to approach this question from a different angle:
Userobject only going to exist for this application?If the
Useris a concept that resides entirely inside of this domain, then there’s no reason to have aUserSettingsaggretate root that has a 1:1 relationship with aUser; you simply makeUser.Settingsa way to retrieve theUserSettingsfor thatUser. (And of course that obviates the need for a repository – it becomes the responsibility of theUserRepositoryto hydrate theUserSettingswhen it hydrates everything else on theUser.)But, if the
Userwill eventually inform sessions for multiple domains, thenUserneeds to represent its own domain, the services of which your application will consume. Then, you gain a very real need to separate theUserSettingsof this application from those of a different application. TheUseris not specific to this application, but theUserSettingsfor thatUseris.NOTE – In the interest of not refactoring your project at this point, if the answer to either question 1 or 2 above is “no”, then you should make
UserSettingsa separate aggregate root within the same domain, in order to create a seamless transition when you eventually do moveUserinto its own domain.