Save hooks and global defaults
Global defaults
A district and its schools can share the time zone from the seed. Repeating that default in every blueprint makes it easier for the definitions to drift. options.Default<TBase, TProp> applies it to entities matching a base class or interface. It runs after blueprint Derives and fills only unset properties.
For this example, implement IHasTimeZone on both District and School. Leave their nullable TimeZoneId properties unset in the factories so the default can fill them.
public interface IHasTimeZone
{
string? TimeZoneId { get; set; }
}
public static partial class TestBiome
{
// Share the seed time zone across both entity types and preserve local overrides.
private static readonly BiomeOptions<SchoolSeed> Options =
new BiomeOptions<SchoolSeed>().Default<IHasTimeZone, string?>(
e => e.TimeZoneId,
(_, ctx) => ctx.Seed.TimeZoneId
);
}
A school near the edge of the district uses its own time zone. The test sets that one value. The district and the other school take theirs from the seed.
await TestBiome
.Start(_db, out _)
.AddDistrict(out _)
// Leave the first school unset so the default fills its time zone.
.AddSchools(out var schools, _ => { }, s => s.TimeZoneId = "America/Denver")
.BuildAsync();
var seed = new SchoolSeed("America/Chicago");
var now = DateTimeOffset.UtcNow;
var district = new District
{
Id = $"dist_{Guid.CreateVersion7():N}",
Name = "Riverside Unified",
TimeZoneId = seed.TimeZoneId,
CreatedAtUtc = now,
UpdatedAtUtc = now,
};
var first = new School
{
Id = $"sch_{Guid.CreateVersion7():N}",
DistrictId = district.Id,
Name = "School 1",
Code = "S1",
// Repeat the district's time zone so both rows use the same default.
TimeZoneId = seed.TimeZoneId,
CreatedAtUtc = now,
UpdatedAtUtc = now,
};
var second = new School
{
Id = $"sch_{Guid.CreateVersion7():N}",
DistrictId = district.Id,
Name = "School 2",
Code = "S2",
TimeZoneId = "America/Denver",
CreatedAtUtc = now,
UpdatedAtUtc = now,
};
_db.AddRange(district, first, second);
await _db.SaveChangesAsync();
Defaultneeds explicit type arguments (Default<TBase, TProp>).- The selected property must be directly writable.
initproperties are fine. Anything else throwsArgumentException. - Defaults apply to entities built by blueprints, including the output of an input blueprint, but not its input object. They don't reach aggregate parts or rows added in
BeforeSave. - A default is fill-only. It treats the type's default value (
null,0,false) as unset, so it cannot tell "unset" from an explicit default value.
Save hooks
Some setup rules depend on the whole graph, such as adding an audit row for each student being enrolled. options.BeforeSave can inspect and change the final row list. options.AfterSave runs after a successful save.
var options = new BiomeOptions<SchoolSeed>().BeforeSave(
(save, _) =>
{
// Take a snapshot before appending to the same list.
foreach (var student in save.Entities.OfType<Student>().ToArray())
{
save.Entities.Add(
new EnrollmentAudit
{
DistrictId = student.DistrictId,
StudentId = student.Id,
RecordedAtUtc = student.EnrolledAtUtc,
}
);
}
return ValueTask.CompletedTask;
}
);
| Member | Meaning |
|---|---|
save.Entities | The mutable List<object> about to be saved (seed rows first, then created entities). |
save.Seed | Your seed. |
save.Session | The session, for inspecting what was created (All<T>, Last<T>). |
Hooks run once per BuildAsync, in registration order, and AfterSave only runs when the store's save succeeded.
A hook in action
A test can check when the store sees an audit row. The recording store calls OnSave when it receives the rows and keeps them in Entities for inspection.
// Record the save alongside the hook events so the test can check their order.
var events = new List<string>();
var store = new RecordingStore { OnSave = () => events.Add("save") };
var seed = new SchoolSeed("America/Chicago");
var options = new BiomeOptions<SchoolSeed>()
.BeforeSave(
(save, _) =>
{
events.Add("before");
// Read the student from this scenario to link its audit row.
var enrolled = save.Session.Last<Student>();
save.Entities.Add(
new EnrollmentAudit
{
DistrictId = enrolled.DistrictId,
StudentId = enrolled.Id,
RecordedAtUtc = enrolled.EnrolledAtUtc,
}
);
return ValueTask.CompletedTask;
}
)
.AfterSave(
(_, _) =>
{
events.Add("after");
return ValueTask.CompletedTask;
}
);
await Biome
.Start(seed, options, store)
.AddDistrict(out _)
.AddSchool(out _)
.AddClass(out _)
.AddStudent(out var student)
.BuildAsync();
// Check the order and confirm the audit row reached the store in that save.
await Assert.That(string.Join(",", events)).IsEqualTo("before,save,after");
await Assert
.That(store.Entities.OfType<EnrollmentAudit>().Single().StudentId)
.IsEqualTo(student.Id);
When a hook beats a default
The district's registration process queues an orientation for each student who needs one. If a BeforeSave hook adds that queue entry, the hook supplies its schedule. A blueprint default on OrientationQueueEntry only applies when a blueprint builds the row.
private static readonly BiomeOptions<SchoolSeed> Options =
new BiomeOptions<SchoolSeed>().BeforeSave(
(save, _) =>
{
var entries = save
.Entities.OfType<Student>()
.Where(s => s.NeedsOrientation)
.Select(s => new OrientationQueueEntry
{
DistrictId = s.DistrictId,
StudentId = s.Id,
// Supply the schedule here because this row skips blueprint defaults.
ScheduledAtUtc = s.EnrolledAtUtc.AddDays(1),
})
.ToArray();
save.Entities.AddRange(entries);
return ValueTask.CompletedTask;
}
);
BeforeSave skip traits, Derives, and global defaults, so the hook must supply every required property.