Migrate from another library
A migration can go one type at a time: a value object from this library sits next to a primitive or another library's type without either noticing. The wire format does not change either — every library on this page writes a single-value object as its bare underlying value — so API clients see nothing.
After converting a type, point the contract kit at it with the values your old tests used: it checks that the new type accepts and rejects what the old one did, and round-trips through text and JSON the same way.
From bare primitives
This is the common case, and the one the library exists for.
- Declare the type, moving the rules scattered through validators and controllers onto it: lengths on
the attribute, bounds in
IValueObjectMinimum<T>andIValueObjectMaximum<T>, a pattern inIValueObjectPatternValidator, the rest inValidateValue, any trimming or upper-casing inNormalizeValue. - Change the entity and the contracts, property by property. JSON bodies, route segments and query strings keep the same shape.
- Map it in EF Core with
ConfigureValueObjects. Then read the next migration carefully: aMaxLengthon the type now sizes the column, so a column that was unbounded becomes bounded. That is usually the point, but it is a schema change, and existing rows must fit. - Delete what the type now guarantees: the format checks in validators, the
Trim()calls, the[MaxLength]and[RegularExpression]attributes, the OpenAPI annotations. For payloads that still carry raw text,MustParseAsreplaces them without restating the rules.
From hand-written value objects
Keep the rules, delete the plumbing.
- Move the checks into
NormalizeValueandValidateValue, and turn each thrown exception into a returnedValidationResultwith a code of your own. - Delete the constructor,
Equals,GetHashCode, the operators,ToString,Parse, and every hand-writtenJsonConverter,TypeConverter, EF Core converter and model binder: the generator writes all of them. - A
record structor a class becomes areadonly partial struct. Where a class could benull, useT?.
From Vogen
| Vogen | AdCodicem.ValueObjects |
|---|---|
[ValueObject<string>] partial class or struct | [ValueObject<string>] readonly partial struct |
private static string NormalizeInput(string input) | public static string NormalizeValue(string value), with IValueObjectNormalizer<string> |
private static Validation Validate(string input) | public static ValidationResult ValidateValue(in string value), with IValueObjectValidator<string> |
Validation.Ok / Validation.Invalid("…") | ValidationResult.Success / ValidationResult.Failure("code", "…") |
Iban.From(raw) | Iban.Create(raw) |
Iban.TryFrom(raw, out var iban) | Iban.TryCreate(raw, out var iban) |
ValueObjectOrError<Iban> result = Iban.TryFrom(raw) | Iban.TryCreate(raw, out var iban, out var validation) |
ValueObjectValidationException | ValueObjectException, which also carries ErrorCode |
| Explicit casts, both ways by default | Opt in with ExplicitConversionFromValue and ImplicitConversionToValue |
Conversions.EfCoreValueConverter, HasVogenConversion() | ConfigureValueObjects(assembly), once |
Conversions.DapperTypeHandler | ValueObjectDapper.AddValueObjectHandlers(assembly), once |
Conversions.Bson, BsonSerializationRegisterFor….TryRegister() | ValueObjectBson.Register(assembly), once, after the GuidSerializer: MongoDB |
Conversions.NewtonsoftJson | settings.AddValueObjects(), which adds ValueObjectConverter to the serializer settings |
Conversions.MessagePack | options.WithValueObjects(), once, on the serializer options, which reads through the rules; UseValueObjects() for SignalR: MessagePack and SignalR |
Conversions.XmlSerializable | [assembly: ValueObjectXmlSerialization], once for the assembly, which reads through the rules: XML |
new VogenTypesFactory() in the options of a source-generated context | [JsonSourceGenerationOptions(Converters = [typeof(ValueObjectJsonConverterFactory)])] |
A length or pattern check inside Validate | MinLength, MaxLength on the attribute; a [GeneratedRegex] through IValueObjectPatternValidator |
Side by side, a normalized and validated IBAN:
// Vogen
[ValueObject<string>(conversions: Conversions.Default | Conversions.EfCoreValueConverter)]
public partial class Iban
{
private static string NormalizeInput(string input) => input.Replace(" ", "").ToUpperInvariant();
private static Validation Validate(string input)
=> input.Length is >= 15 and <= 34
? Validation.Ok
: Validation.Invalid("An IBAN has between 15 and 34 characters.");
}
// AdCodicem.ValueObjects
[ValueObject<string>(MinLength = 15, MaxLength = 34)]
public readonly partial struct Iban : IValueObjectNormalizer<string>
{
public static string NormalizeValue(string value) => value.Replace(" ", "").ToUpperInvariant();
}
The length check needs no code any more, and it now sizes the column and documents the schema too.
Three differences to plan for:
- EF Core reads. Vogen validates values read from the database by default; this library does not. If other
systems write to your tables, keep that behaviour with
ConfigureValueObjects(strict: true, …). - Instances. A Vogen instance may deliberately hold a value that
Validatewould refuse, as a sentinel. There is no such escape hatch here: express absence asIban?, and name valid values with[KnownValue]. - Underlying types. Vogen wraps any type; this library supports 22. A value object over a
Urior a type of your own has no direct equivalent.
From StronglyTypedId
| StronglyTypedId | AdCodicem.ValueObjects |
|---|---|
[StronglyTypedId] partial struct OrderId (a Guid) | [ValueObject<Guid>] readonly partial struct OrderId |
[StronglyTypedId(Template.String)] | [ValueObject<string>] |
new OrderId(guid) | OrderId.Create(guid): the constructor is private, so the rules cannot be skipped |
OrderId.New() | A New() of your own, below — or an [EntityId] for an identifier clients see |
OrderId.Empty | OrderId? for absence; default(OrderId) is now a build error |
new OrderId.EfCoreValueConverter(), one per type | ConfigureValueObjects(assembly), once |
.HasConversion(...).ValueGeneratedOnAdd() on a key | HasValueObjectKeyGeneration(), which keeps the provider's sequential GUIDs, or its identity column for an int or a long identifier; a Guid key left unset is refused |
SqlMapper.AddTypeHandler(new OrderId.DapperTypeHandler()), one per type | ValueObjectDapper.AddValueObjectHandlers(assembly), once |
| Converters passed to a source-generated context's options | [JsonSourceGenerationOptions(Converters = [typeof(ValueObjectJsonConverterFactory)])] |
[ValueObject<Guid>]
public readonly partial struct OrderId : IValueObjectValidator<Guid>
{
public static OrderId New() => CreateUnchecked(Guid.CreateVersion7());
public static ValidationResult ValidateValue(in Guid value)
=> value == Guid.Empty
? ValidationResult.Required("An order identifier must not be empty.")
: ValidationResult.Success;
}
The validator is new: StronglyTypedId has no validation, so an empty Guid was a valid identifier. Once the
types are converted, remove the StronglyTypedId and StronglyTypedId.Templates packages and any .typedid
templates.
From Thinktecture.Runtime.Extensions
- The validation hook splits in two.
ValidateFactoryArguments(ref ValidationError? validationError, ref string value)both normalizes, by assigningvalue, and validates. Move the assignment intoNormalizeValueand the checks intoValidateValue, returning aValidationResultinstead of setting an error. - String comparison changes. Thinktecture compares string keys case-insensitively by default; this library
compares ordinally. To keep the behaviour, declare
Comparison = StringComparison.OrdinalIgnoreCase— or, better, normalize the case so the stored value is canonical. - A class becomes a
readonly partial struct.nullchecks becomeT?. - EF Core.
UseThinktectureValueConverters()becomesConfigureValueObjects(assembly)inConfigureConventions. Both skip validation on read by default. - Serilog.
Destructure.UsingThinktectureRuntimeExtensions()becomesDestructure.ValueObjects(), fromAdCodicem.ValueObjects.Serilog, which logs a value object with@,{@Value}, as the value it carries. ItsCaptureAsUnderlyingValueoption covers{Value}, without@, too, which Thinktecture's policy leaves toToString(): Serilog. - MessagePack.
ThinktectureMessageFormatterResolverbecomesWithValueObjects()on the serializer options, fromAdCodicem.ValueObjects.MessagePack, which reads through the rules unless asked to trust the bytes, andUseValueObjects()on SignalR's MessagePack hub protocol: MessagePack and SignalR. - ProtoBuf. Thinktecture's ProtoBuf package, which stopped at a beta, becomes
AddValueObjectson the protobuf-net model, fromAdCodicem.ValueObjects.ProtobufNet, which writes each value object as its underlying type and reads it through the rules: protobuf-net and code-first gRPC. - Smart enums and unions stay where they are. Only single-value value objects have an equivalent here; a closed set of codes can become a value object with known values.
From the options written as text of an earlier version
Earlier versions read four rules off [ValueObject<T>] and [KnownValue] as text, which the generator parsed under
a grammar of its own and the compiler knew nothing of. Each is now declared as a value the compiler checks, and the
old form is a compile error that names its replacement, which any minor version may remove before 1.0.0. Move one type
at a time; the contract kit, pointed at the type with the values its tests already use, checks that it accepts and
rejects what it did.
The pattern
Pattern = "..." built its Regex at run time, which native AOT interprets, and is VO0021. Move each pattern to
IValueObjectPatternValidator:
[ValueObject<string>(MinLength = 15, MaxLength = 34, Pattern = "^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$")]
public readonly partial struct Iban;
becomes:
using System.Text.RegularExpressions;
[ValueObject<string>(MinLength = 15, MaxLength = 34)]
public readonly partial struct Iban : IValueObjectPatternValidator
{
[GeneratedRegex("^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 1000)]
public static partial Regex Pattern { get; }
}
Copy the expression as it was, and keep RegexOptions.CultureInvariant and the timeout of 1000 milliseconds:
they are what the option used, so the type accepts and rejects the same values, with the same
value_object.invalid_format and the same message, and its OpenAPI pattern is unchanged.
Diagnostics has the rest.
The bounds
Minimum = "..." and Maximum = "..." are VO0028. Declare each bound as a static property of the underlying type
through IValueObjectMinimum<T> and IValueObjectMaximum<T>, public static DateOnly Minimum => new(1900, 1, 1);.
Moving off Minimum and Maximum shows the change, and
the one difference a client may see: the message quotes a real, a time or a date and time in its round-trip form.
The known values
[KnownValue("France", "FR")] on the type is VO0034. Each known value becomes a member of the type, initialized
through the generated Known:
[ValueObject<string>(ValueSet = ValueSetKind.Closed, MinLength = 2, MaxLength = 2)]
public readonly partial struct CountryCode
{
[KnownValue(Description = "Mainland France and its overseas departments.")]
public static readonly CountryCode France = Known("FR");
}
The code fix of VO0034 writes it, with the value as an expression of the underlying type, for every attribute of
a document, a project or the solution at once. The names, the order, the descriptions and the schema are unchanged;
the known values were generated properties and are now your fields, which only a reflection over the type's
properties notices. Known values has the rules a member follows.
The example
Example = "..." on [ValueObject<T>] or [EntityId] is VO0035. Implement IValueObjectExample<TSelf>, whose
example the type's own rules create, public static Iban Example => Create("FR7630006000011234567890189");. The
OpenAPI document publishes the same value.