Instantly share code, notes, and snippets.

@vkhorikov /1.cs
Last active Dec 24, 2018

Embed
What would you like to do?
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