In the previous article I’ve talked about the use of a Value Object and you’ve seen the advantages of a value object in practice. One challenge that occurs is regarding saving value objects in a database. And you will see why. Let’s define our entity class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
public class Email : ValueObject<string> { public Email() { //for expando deserializer } public Email(SerializationInfo info, StreamingContext context) { //The special constructor is used to deserialize values. this.GetObjectData(info, context); } public static Email Create(string value) { return new Email { Value = value }; } public override int CompareTo(ValueObject<string> other) { return this.Value.CompareTo(other.Value); } protected override bool EqualsCore(object obj) { if (obj is null) return false; if (obj is ValueObject<string> vo) { return this.Value == vo.Value; } return false; } protected override int GetHashCodeCore() { return this.Value.GetHashCode(); } protected override void Validators(ValidationBuilder<string, string> validators) { validators.Add(x => (!string.IsNullOrEmpty(x)) ? ValidationResult<string>.Success() : ValidationResult<string>.Fail("Email cannot be empty"), 0); } } |
1 2 3 4 5 |
public class ContactDetails : BasicEntity { [BsonElement("Email")] public Email Email { get; set; } } |
This model contains an email value object.Read more