Skip to content

Instantly share code, notes, and snippets.

@vkhorikov
Last active December 24, 2018 16:05
Show Gist options
  • Save vkhorikov/a46c20ffc3d7f9c30d5a0f77f46610ad to your computer and use it in GitHub Desktop.
Save vkhorikov/a46c20ffc3d7f9c30d5a0f77f46610ad to your computer and use it in GitHub Desktop.
Hierarchy of value objects
public class Person : Entity
{
public virtual string Name { get; set; }
public virtual Document Document { get; set; }
}
public class Document : Entity
{
}
public class IdentityCard : Document
{
public virtual DateTime IssueDate { get; set; }
}
public class Passport : Document
{
public virtual string SerialNumber { get; set; }
}
var person = new Person { Name = "Name" };
person.Document = new IdentityCard(DateTime.Now);
Flush(); // both the person and the document are created
person.Document = new Passport("Serial Number");
Flush(); // the new document is assigned but the old one remains in the database
public class DocumentContainer
{
private DocumentType _type;
private DateTime? _issueDate;
private string _serialNumber;
public Document Document
{
get
{
switch (_type)
{
case DocumentType.IdentityCard:
return new IdentityCard(_issueDate.Value);
case DocumentType.Passport:
return new Passport(_serialNumber);
default:
throw new ArgumentOutOfRangeException();
}
}
set
{
switch (value)
{
case IdentityCard identityCard:
_issueDate = identityCard.IssueDate;
_serialNumber = null;
_type = DocumentType.IdentityCard;
break;
case Passport passport:
_issueDate = null;
_serialNumber = passport.SerialNumber;
_type = DocumentType.Passport;
break;
}
}
}
}
public class Person : Entity
{
public virtual string Name { get; set; }
private readonly DocumentContainer _document;
public virtual Document Document
{
get => _document.Document;
set => _document.Document = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment