Is it possible for an Aggregate root entity to have a method in which it will call a Repository?
I know it should not but want to get confirmed as Eric's book is also not saying anything clearly :(
one more thing where can I get a unit testing example for domain-driven design?
This is a bit of a religious question.
Some see no problem with this, while others might believe it is heresy to do so.
While I've normally always kept my Repository away from my Domain Model (and had an upstream service object deal with the Repository), I have had a project that "required" having the Repository accessable from the Domain Model.
This was due to the Domain object needing to retrieve specific data based on business logic => using specification objects/Linq to nHibernate (the responsibility and knowledge of how to filter data belonged to that Domain Object) and/or performance reasons.
A caveat around doing this is how to get the reference to the Repository to the Domain object - in that case I utilized Constructor injection with an IOC tool.
Whether you should do this or not really depends on your solution/use case/technologies being used etc...
Can? -Yes.
Should? -No.
All answers are however context-sensitive, and you don't provide yours.
A generic advise would be to look for a "service" or "specification" type.
Behavior IS-WHAT-IT-IS. Eric calls a Repository like utility from a Brokerage Account entity called, "QueryService". He mentions that it's not a good design for a real project. So what do you do?
public class Clerk
{
public Clerk()
{
}
//Store Report in Database
public void File(Report);
{
ReportRepository.Add(Report);
}
}
You could do that, but it's probably best to tell the Clerk which Repository to use.
public class Clerk
{
private IReportRepository _reportRepository;
public Clerk(IReportRepository ReportRepository)
{
this._reportRepository = ReportRepository
}
//Store Report in Database
public void File(Report);
{
this._reportRepository.Add(Report);
}
}
Related
I am currently trying out DDD and reading Evans book. I have arrived at a model that has an aggregate whose root is Student. Now I need to have (or be able to distinguish) a RegisteredStudent and an EnrolledStudent (inherits RegisteredStudent). I don't know how to handle inheritance in DDD.
Should the 2 inherited classes be inside the aggregate? If so, are they also considered aggregate roots since their identity is the same as the root (there are only added properties to them)? If not, how do I give access to them from other entities?
Or should I not be using inheritance? Why?
And also, what if you have an entity in an aggregate that isn't a root, but you need it to inherit an entity outside? How should you go about it?
What you need to ask yourself here is whether a RegisteredStudent and an EnrolledStudent are different concepts. Are they not both students, but just in a different state?
In general, you should favor composition over inheritance.
Here's an example of what I would do. (Note that it's just my example, I don't know the domain, so it's not a definitive solution).
You could have a Student class, which is your aggregate root and then a few different state classes: Registered and Enrolled. That way you don't need to expose these state classes on the student but you could just expose methods on the Student. A small example in C#:
class Student
{
State _currentState;
void Enroll()
{
if(!_currentState is Registered)
throw new InvalidOperationException("Cannot enroll student who is not registered");
this._currentState = new Enrolled();
}
void Register(string name)
{
this._currentState = new Registered(name);
}
}
class StudentState{}
class Enrolled : StudentState
{}
class Registered : StudentState
{
public Registered(string name)
{
Name = name;
}
public string Name {get; private set;}
}
This is a simple application of the State design pattern, you could externalize more parts of it and build a complete state-machine, but I'll leave that up to you. (Also it's typed directly in to the SO-editor, so there could be syntax errors)
EDIT after comments
Whether you need to expose a State-property or not depends on the context. In general I would recommend not to do that, because you're exposing the internals of the Student. It would be better to expose a method called CanEnroll for example. That way you can change the internal implementation of your state pattern without affecting any clients.
As for question 3, it's hard to say without a use case. However, here are some guidelines:
Favor composition over inheritance (again, I know).
You can have a reference from inside an aggregate to the outer world, you shouldn't have a reference the other way around though.
I am using domain-driven design and I have a pretty clear picture of my domain model. It contains over 120 classes and it is quite stable. We will implement it in .NET 4 and C#. The thing is, we need the model to be multilingual; some of the attributes need to be stored in multiple languages. For example, the Person class has a Position property of type string which should store a value in English (e.g. "Librarian") and Spanish (e.g. "Bibliotecario"). The getter for this property should return the English or Spanish version depending on some language parameter.
And here begin my questions. I am not sure how to parameterize this. I have exlpored two major ways to do it:
Use property collections. Position would not be a string but rather a Dictionary<Language, string>, which would let clients retrieve the person's position by language.
Keep simple, scalar properties, but make them return (or set) the value for one language or another depending on a globally known "current language" setting. The client code would set the working language, and then all objects would set and get values in that language.
Option 1 avoids global state, but it messes up the interface of almost every class in my model. On the other hand, option 2 is less expressive, since you can't tell what language you're going to get without looking at the global setting. Also, it introduces a dependency into every class on the global setting.
Please note that I am not interested in database or ORM implementations; I am working at the domain model level only.
I have two specific questions then:
Which is the best option (1 or 2) to achieve my goal of a multilingual domain model?
Are there other options that I haven't considered, and which are they?
Thank you.
Edit. Some have suggested that this is a user interface related issue, and thus can be tackled through globalisation/localisation support in .NET. I disagree. UI localisation works only if you know the localised literals that must be shown to the user at compile time, but this is not our case. My question involves multilingual data that is unknown at compile time, because it will be provided as user data at run-time. This is not a UI-related issue.
Edit 2. Please bear in mind that the Person.Position is just a toy example to illustrate the question. It's not part of the real model. Don't try to criticise it or improve upon it; there is no point in doing that. Our business requirements involve a lot of attributes that cannot be encoded as enum types or similar, and must stay as free text. Hence the difficulty.
Given the following:
Some use case involve setting the values for an object in all the
supported languages; others involve looking at the values in one given
language.
I would suggest going for both options. That means that the Person and all classes that hold multilingual content should keep that content in their state and:
The Position property should set/get the person's position in the
current user's language.
There should be a corresponding property or method for all
language setting/getting.
There should be a method for setting (or even switching if needed)
the user language. I would create an abstract class (e.g.
BaseMultilingualEntity) with an abstract SetLanguage(Language
lang) method and a CurrentLanguage getter. You need to keep
track of all the objects that derive from BaseMultilingualEntity
in some sort of registry that would expose language setting.
EDIT WITH SOME CODE
public enum Language {
English,
German
}
// all multilingual entity classes should derive from this one; this is practically a partly implemented observer
public abstract class BaseMultilingualEntity
{
public Language CurrentLanguage { get; private set; }
public void SetCurrentLanguage(Language lang)
{
this.CurrentLanguage = lang;
}
}
// this is practically an observable and perhaps SRP is not fully respected here but you got the point i think
public class UserSettings
{
private List<BaseMultilingualEntity> _multilingualEntities;
public void SetCurrentLanguage(Language lang)
{
if (_multilingualEntities == null)
return;
foreach (BaseMultilingualEntity multiLingualEntity in _multilingualEntities)
multiLingualEntity.SetCurrentLanguage(lang);
}
public void TrackMultilingualEntity(BaseMultilingualEntity multiLingualEntity)
{
if (_multilingualEntities == null)
_multilingualEntities = new List<BaseMultilingualEntity>();
_multilingualEntities.Add(multiLingualEntity);
}
}
// the Person entity class is a multilingual entity; the intention is to keep the XXXX with the XXXXInAllLanguages property in sync
public class Person : BaseMultilingualEntity
{
public string Position
{
set
{
_PositionInAllLanguages[this.CurrentLanguage] = value;
}
get
{
return _PositionInAllLanguages[this.CurrentLanguage];
}
}
private Dictionary<Language, string> _PositionInAllLanguages;
public Dictionary<Language, string> PositionInAllLanguages {
get
{
return _PositionInAllLanguages;
}
set
{
_PositionInAllLanguages = value;
}
}
}
public class Program
{
public static void Main()
{
UserSettings us = new UserSettings();
us.SetCurrentLanguage(Language.English);
Person person1 = new Person();
us.TrackMultilingualEntity(person1);
// use case: set position in all languages
person1.PositionInAllLanguages = new Dictionary<Language, string> {
{ Language.English, "Software Developer" },
{ Language.German, "Software Entwikcler" }
};
// use case: display a person's position in the user language
Console.WriteLine(person1.Position);
// use case: switch language
us.SetCurrentLanguage(Language.German);
Console.WriteLine(person1.Position);
// use case: set position in the current user's language
person1.Position = "Software Entwickler";
// use case: display a person's position in all languages
foreach (Language lang in person1.PositionInAllLanguages.Keys)
Console.WriteLine(person1.PositionInAllLanguages[lang]);
Console.ReadKey();
}
}
A domain model is an abstraction - it models a specific part of the world, it captures the concepts of a domain.
The model exists so developers can communicate in code the way domain experts communicate - using the same names for the same concepts.
Now, a Spanish expert and an English expert may use different words for the same concept, but the concept itself would be the same (one hopes, though language can be ambiguous and people do not always understand the same concept in the same way, but I digress).
The code should pick one human language for these concepts and stick to it. There is absolutely no reason for the model to consist of different languages in order to represent a single concept.
Now, you may need to show users of the application data and meta data in their language, but the concept does not change.
In this regard, you second option is the thing you should be doing - with .NET, this is normally done by looking at the CurrentThread.CurrentCulture and/or CurrentThread.CurrentUICulture and by using satellite assemblies that will contain localized resources.
My question involves multilingual data
[...]
Please note that I am not interested in database or ORM
implementations;
I can see a bit of contradiction in these 2 statements. Whatever the final solution, you'll have multilingual-specific structures in your database anyway as well as a mechanism that queries them to do the translation, right ?
The thing is, unless your domain really is about translation, I would try to keep it away from multilingual concerns as much as possible, for the same reason that you would try to make your domain persistence ignorant or UI ignorant.
Thus I would at the very least place the multilingual resolution logic in the Infrastructure layer. You could then for instance use aspects to only attach multilingual behavior to some properties, if you really need a trace of multi-language in your entities and don't want your persistence layer to handle all that transparently :
public class Person
{
[Multilingual]
public string Position { get; set; }
}
It contains over 120 classes and it is quite stable.
Not directly related to question, but you might want to consider the existence of multiple bounded contexts in your domain.
I agree with Oded that it seems in your scenario, language is a UI concern. Sure, the domain may be declared via combination of C# and English, what it represents is abstract. The UI would handle language with CultureInfo.CurrentCulture - effectively option #2.
A Person entity having a Position property doesn't govern the natural language used to represent the position. You may have a use case where you'd want to display a position in one language while it is originally stored in another. In this case, you can have a translator as part of the UI. This is similar to representing money as a pair of an amount and currency and then converting between currencies.
EDIT
The getter for this property should return the English or Spanish
version depending on some language parameter.
What determines this language parameter? What is responsible for ensuring that, say Position, is stored in multiple languages? Or is translation to be performed on the fly? Who is the client of the property? If the client determines the language parameter, why can't the client perform the translation without involving the domain? Are there any behaviors associated with multiple languages or is this only a concern for reading purposes? The point of DDD is to distill your core behavioral domain and shifts aspects related to querying data into other areas of responsibility. For example, you can use the read-model pattern to access the Position property of an aggregate with a specific language.
Make the User explicit!
I already encountered domains where the user's culture is a first class citizen in the domain but, in such situations, I model a proper value object (in your example I would use a Position class properly implementing IEquatable<Position>) and the User that is able to express such values.
Sticking to your example, something like:
public sealed class VATIN : IEquatable<VATIN> { // implementation here... }
public sealed class Position : IEquatable<Position> { // implementation here... }
public sealed class Person
{
// a few constructors here...
// a Person's identifier from the domain expert, since it's an entity
public VATIN Identifier { get { // implementation here } }
// some more properties if you need them...
public Position CurrentPosition { get { // implementation here } }
// some commands
public void PromoteTo(Position newPosition) { // implementation here }
}
public sealed class User
{
// <summary>Express the position provided according to the culture of the user.</summary>
// <param name="position">Position to express.</param>
// <exception cref="ArgumentNullException"><paramref name="position"/> is null.</exception>
// <exception cref="UnknownPositionException"><paramref name="position"/> is unknown.</exception>
public string Express(Position position) { // implementation here }
// <summary>Returns the <see cref="Position"/> expressed from the user.</summary>
// <param name="positionName">Name of the position in the culture of the user.</param>
// <exception cref="ArgumentNullException"><paramref name="positionName"/> is null or empty.</exception>
// <exception cref="UnknownPositionNameException"><paramref name="positionName"/> is unknown.</exception>
public Position ParsePosition(string positionName) { // implementation here }
}
And don't forget documentation and properly designed exceptions!
WARNING
There are at least two huge design smells in the sample model that you provided:
a public setter (the Position property)
a System.String holding business value
A public setter means either that your entity exposes its own state to clients regardless of its own invariants, or that such a property has no business value for the entity and thus should not be part of the entity at all. Indeed, mutable entities should always separate commands (that can change the state) and queries (that cannot).
A System.String with business semantic always smells of a domain concept left implicit, typically a value-object with equality operations (that implements IEquatable, I mean).
Be aware that a reusable domain model is quite challenging to obtain, since it requires more than two domain experts and a strong experience in ddd modeling. The worst "domain model" that I faced in my carreer was designed by a senior programmer with huge OOP skills but no previous modeling experience: it was a mix of GoF patterns and data structures that, in the hope to be really flexible, proved to be useless. After 200k €, spent in that effort, we had to throw it away and restart from scratch.
May be that you just need a good data model directly mapped to a set of simple data structures in C#: you'll never have any ROI from an upfront investment in a domain model, if you don't really need it!
It might be worth mentioning Apache's MultiViews feature and the way it delivers different content based on the browser's Accept-Language header.
So if a user requests 'content.xml', for example, Apache will deliver content.en.xml or content.sp.xl or content.fr.xml or whatever is available based on some prioritization rules.
Given the requirements I would probably try to model the position as an entity/value on its own. This object would not be a dictionary of translations but rather just be usable as a key into a domainDictionary.
// IDomainDictionary would be resolved based on CurrentThread.CurrentUICulture
var domainDict = container.Resolve<IDomainDictionary<Position>>();
var position = person.Position;
Debug.Writeline(domainDict.NameFor(position, pluralForm: 1));
Now assuming you need to dynamically create new positions when a suitable synonym doesn't exist you could probably keep the data somewhat tidy by using the IDomainDictionary as an source for auto complete suggestions in the UI.
I'm faced with an architecture decisions wich are quite tricky to solve. I'm sorry in advance for a long post but before you can help me I have to give you a context.
My company tries to integrate new architecture (based around ASP.NET MVC framework) into the existing ASP.NET legacy code. The hint is that we can't get rid of all the business code wich is encapsulated in the legacy assemblies but we have to wrap it into the new ones in order to make a sort of "anticorruption" layer and to decouple it. We're good until now, but here come one constraint (the main) that makes the decoupling a bit tricker :
In the legacy ASP.NET web site, they used a kind of persistance aware model in order to enable lazy loading from views (I know it's crap). There is a reason for it. The code is so convulted and difficult to deploy that they wanted to give a possibility to designers to modify only views without deploying binaries. A God class is pushed into the view with properties that are lazy loaded if needed. So for example if a designer wants to modify a view to display another property he can just pick whetever he wants from the God class and it just works. We have to keep the same behavior in the new MVC architecture.
Let's take an example. Let's say we have a Item legacy persistance aware DTO :
public class Item
{
public string Title {get; set; }
public List<UserComment> Comments {get; set; } // lazy loaded in the background in legacy code.
}
So the designer uses in the view can call a Item.Title and deploy and after can add if he wants Item.Comments (in foreach) and deploy just the view without the need of deploying all the binaries.
The following architecture has been proposed. A new POCOs for the mvc web site are located in the Domain assebmly which doesn't reference any other assembly. In this assembly we have also a definition of repositories interfaces like IItemRepository. Entities are used directly in the ASP.NET MVC ViewModels and obtained through the Repository implementations that are wired up by the underlying DI container.
We have another assebly where the implementations of IRepositories live. That assembly references all the legacy code that is used to populate the entities from the Domain.
Untill now all is great. But here's the tricky part. The entities from the domain assembly should comply with the constraint from the point 1 (lazy load in the views).
So our POCOs declare all the properties as Lazy<>. Which allows us in the implementation assembly (the one that references all the legacy code) to define delegates that populate these properties when they are accessed. Here's the new implementation of POCOs for MVC :
public class Item
{
public string Title {get; set; }
public Lazy<List<UserComment>> Comments {get; set; } // lazy loaded in the background in legacy code.
}
And here is a ItemRepository implementation :
public class ItemRepository : IItemRepository
{
public Item GetItem(int id)
{
Item i = new Item() { Id = id };
i.Comments = new System.Lazy<IEnumerable<UserComments>>( () => CommentsService.GetUserComments(id));
return i;
}
}
We don't like it very much, and here's why :
POCOs are not really POCO because it seems that there is a leaky abstraction of lifetime managment in the entities. This is not a big deal because Lazy<>, is a type in .NET Framework. On the other hand if you're using an ORM like NHibernate you have to bend your POCOs in order to allow NHibernate to load the data (sepcial constructor, virtual members, etc.)
The other reason why we don't like it, is that it hides the underlying service composition in the repositories implementation. For example if Item.Comments is used, in the underlying implementation of the ItemRepository we will call to another legacy service (CommentsService.GetUserComments(id) in that case)
Question 1 : Do you see other drawbacks in using Lazy<> in the POCO implementation ? Or other flaws in the design that we should consider ?
Question 2 : How can we avoid legacy service composition in the repository implementations in order to have a clear "vision" of which
legacy services are used ? Besides, do we really need this "vision"
at the implementation level as we could consider repositories
implementation as "façade" to the legacy services ?
Question 3 : Are there any other alternatives with a respect to the constraint 1 (lazy load) ?
Question 4 : Are there any guidelines related to the composition for the lazy members ?
I'm sorry for the long questions but would really appreciate your help.
Thomas
Does the lazy-loading properties have to be List<T>? If not, you could define them as IList<T> or ICollection<T>, like this:
public class Item
{
public string Title {get; set; }
public IList<UserComment> Comments {get; set; }
}
Now, since the property is an instance of an interface, you could create a Virtual Proxy out of it.
I'm trying to figure out how to accomplish the following:
User can have many Websites
What I need to do before adding a new website to a user, is to take the website URL and pass it to a method which will check whether the Website already exist in the database (another User has the same website associated), or whether to create a new record. <= The reason for this is whether to create a new thumbnail or use an existing.
The problem is that the repository should be per aggregate root, which means I Cant do what I've Explained above? - I could first get ALL users in the database and then foreach look with if statement that checks where the user has a website record with same URL, but that would result in an endless and slow process.
Whatever repository approach you're using, you should be able to specify criteria in some fashion. Therefore, search for a user associated with the website in question - if the search returns no users, the website is not in use.
For example, you might add a method with the following signature (or you'd pass a query object as described in this article):
User GetUser(string hasUrl);
That method should generate SQL more or less like this:
select u.userId
from User u
join Website w
on w.UserId = u.UserId
where w.Url = #url
This should be nearly as efficient as querying the Website table directly; there's no need to load all the users and website records into memory. Let your relational database do the heavy lifting and let your repository implementation (or object-relational mapper) handle the translation.
I think there is a fundamental problem with your model. Websites are part of a User aggregate group if I understand correctly. Which means a website instance does not have global scope, it is meaningful only in the context of belonging to a user.
But now when a user wants to add a new website, you first want to check to see if the "website exists in the database" before you create a new one. Which means websites in fact do have a global scope. Otherwise anytime a user requested a new website, you would create a new website for that specific user with that website being meaningful in the scope of that user. Here you have websites which are shared and therefore meaningful in the scope of many users and therefore not part of the user aggregate.
Fix your model and you will fix your query difficulties.
One strategy is to implement a service that can verify the constraint.
public interface IWebsiteUniquenessValidator
{
bool IsWebsiteUnique(string websiteUrl);
}
You will then have to implement it, how you do that will depend on factors I don't know, but I suggest not worrying about going through the domain. Make it simple, it's just a query (* - I'll add to this at the bottom).
public class WebsiteUniquenessValidator : IWebsiteUniquenessValidator
{
//.....
}
Then, "inject" it into the method where it is needed. I say "inject" because we will provide it to the domain object from outside the domain, but .. we will do so with a method parameter rather than a constructor parameter (in order to avoid requiring our entities to be instantiated by our IoC container).
public class User
{
public void AddWebsite(string websiteUrl, IWebsiteUniquenessValidator uniquenessValidator)
{
if (!uniquenessValidator.IsWebsiteUnique(websiteUrl) {
throw new ValidationException(...);
}
//....
}
}
Whatever the consumer of your User and its Repository is - if that's a Service class or a CommandHandler - can provide that uniqueness validator dependency. This consumer should already by wired up through IoC, since it will be consuming the UserRepository:
public class UserService
{
private readonly IUserRepository _repo;
private readonly IWebsiteUniquenessValidator _validator;
public UserService(IUserRepository repo, IWebsiteUniquenessValidator validator)
{
_repo = repo;
_validator = validator;
}
public Result AddWebsiteToUser(Guid userId, string websiteUrl)
{
try {
var user = _repo.Get(userId);
user.AddWebsite(websiteUrl, _validator);
}
catch (AggregateNotFoundException ex) {
//....
}
catch (ValidationException ex) {
//....
}
}
}
*I mentioned making the validation simple and avoiding the Domain.
We build Domains to encapsulate the often complex behavior that is involved with modifying data.
What experience shows, is that the requirements around changing data are very different from those around querying data.
This seems like a pain point you are experiencing because you are trying to force a read to go through a write system.
It is possible to separate the reading of data from the Domain, from the write side, in order to alleviate these pain points.
CQRS is the name given to this technique. I'll just say that a whole bunch of lightbulbs went click once I viewed DDD in the context of CQRS. I highly recommend trying to understand the concepts of CQRS.
The shorter version of the Question: "Is it ok to have a superclass, with 2 subclasses, one is an entity the other is a Value Object?"
To longer version:
T have a Team superclass. The Team has the Master, Helpers and a Code.
Then i have the DefaultTeam, subclass of Team, which is an entity with an unique **Code**** has its domain identity.
Then i have the **ExecutionTeam, its a subclass of Team and has an extra attribute OriginalTeam:
public abstract class Team{
public string Code{ get; protected set; }
public Worker Master{ get; protected set; }
public IList<Worker > Helpers { get; protected set; }
...
}
public class DefaultTeam: Team
{
}
public class ExecutionTeam : Team
{
public virtual string Code { get { return OriginalTeam.Code; } }
public virtual DefaultTeam OriginalTeam { get; private set; }
...
}
The ExecutionTeam, is the team that executes a Task.
When a Task needs to be executed, we choose a DefaultTeam to execute it.
But we can change the Helpers from the DefaultTeam (the master never changes).
That team that executes the task, is a variation of the DefaultTeam (OriginalTeam), but with the Helpers that were chosen just for that Task.
The ExecutionTeam will have the same code has the OriginalTeam. So the ExecutionTeam has no unique identity.
If there are 10 executions of tasks by the same DefaultTeam, there will be 10 ExecutionTeams with the same code (with the same OriginalTeam). So ExecutionTeam is cannot be an Entity.
But having an Entity and a Value Object sharing the same superclass (both being Teams), is a bit strange. Maybe this domain model has something wrong.
Need opinions.
Thanks
What is it that makes the DefaultTeam a Value Object rather than an Entity? Isn't a DefaultTeam also an entity?
That being said, here are some comments:
Why do you need a special class for DefaultTeam? Can't a DefaultTeam simply be an ExecutionTeam, with certain specified values?
A DefaultTeam should probably be an instance of a Team that is associated with an application domain. For example, you might have a particular team that is generally used to solve problems with Project XYZ.
Instead of listing "DefaultTeam" as a property of the ExecutionTeam, you should probably have a "PreviousTeam" as a property of both the Team and ExecutionTeam classes.
This will be more generalizable, in case the team gets changed yet again.
Since Task is an important part of the domain and is assigned to a Team, it should probably be a property of Team.
"Helpers" doesn't seem an appropriate name for the team members. Why not just name them "Members" or "TeamMembers"?
"Master" is probably un-PC unless you are working in Dilbert land or dealing with a database :) You might want to change this to "Supervisor" or "Manager".
"Code" is probably a bad name in the context of your application, as it may easily be confused with programming code. You might want to use "Id" or "TeamId" instead.
Sounds like ExecutionTeam might be better modeled as an interface ICanExecuteTasks. Would that work for you? It would eliminate the issue you are struggling with..
As to your short question, if the ExecutionTeam was indeed a derived class of Team, (inheriting from team and representing an "IsA" relatoonship, then the answer is No, they cannot be of different types because of course, every ExecutionTeam isA Team, thgere is only one thing, which is both a Team and an ExecutionTeam at the same time... It cannot be both an entity Type and a value type at the same time.
But the way you have designed the classes, as you have structured things, ExcecutionTeam is not a derived class, it is a property of the DefaultTeam. This implies that they have a "HasA" relationship. THis implies that they are different, co-existing objects, one of which can be an entity and one of which can be a value type. But my gut tells me this is not an accurate mirror of your real domain model...