persistence records carry data: ClientData/OrderData + domain->persistence mappers

The fake DbContext now stores data-only DbBase subclasses (renamed from
the identity-only Shadow wrappers) and refreshes rows in place on re-Save;
the object graph is flattened to ids in storage.

yak: data-carrying-persistence-records-orderdataclientdata-mappers-tb3a
This commit is contained in:
2026-09-16 18:38:38 +01:00
parent 9895ef87e4
commit 49f4ca395f
4 changed files with 215 additions and 65 deletions
+6 -5
View File
@@ -4,9 +4,10 @@ namespace After;
/// The DB base class still exists in the "after" situation — it is part of the
/// *persistence* layer — but the direction of the dependency is flipped:
/// domain objects (<see cref="Client"/>, <see cref="Order"/>) no longer derive
/// from it. Only the <see cref="DbContext"/>'s own internal shadow entities do,
/// so nothing outside the persistence layer can ever reach a
/// <see cref="DbContext"/> through a domain object.
/// from it. Only the framework's own data-only persistence records do
/// (<see cref="ClientData"/>, <see cref="OrderData"/>): storage wants data
/// without behaviour, so the domain keeps the behaviour and the framework
/// keeps the data — the mappers bridge the two shapes.
/// </summary>
public class DbBase
{
@@ -19,8 +20,8 @@ public class DbBase
/// <summary>
/// Back-reference to the owning <see cref="DbContext"/>. In the after
/// situation this lives only on the context's internal shadow entities —
/// the plain domain objects that used to inherit it no longer do.
/// situation this lives only on the persistence records — the plain
/// domain objects that used to inherit it no longer do.
/// </summary>
public DbContext? DbContext { get; internal set; }
}
+81 -56
View File
@@ -1,95 +1,120 @@
namespace After;
// ---------------------------------------------------------------------------
// Internal shadow wrappers — live *inside* the persistence layer so the
// domain never sees a DbContext back-reference. Subclassed per-entity-type
// solely to make `Set<T>` strongly-typed.
// The persistence side of the "after" situation. The (fake) framework stores
// its own data-only records — <see cref="ClientData"/> / <see cref="OrderData"/>,
// both <see cref="DbBase"/> subclasses — never the domain objects themselves.
// Domain state reaches storage only through explicit mapping; the context keeps
// a reference-identity map so a second <see cref="Save"/> of the same domain
// object refreshes its row instead of duplicating it.
// ---------------------------------------------------------------------------
/// <summary>Lightweight shadow holder kept alive inside the context.</summary>
public abstract class Shadow
/// <summary>
/// Persisted shape of a <see cref="Client"/>: data only — the orders are
/// separate <see cref="OrderData"/> rows, so nothing more is needed here.
/// </summary>
public sealed class ClientData : DbBase
{
/// <summary>ID assigned when first persisted.</summary>
public Guid Id { get; set; }
/// <summary>Back-reference to the owning <see cref="DbContext"/> (internal only).</summary>
public DbContext? DbContext { get; internal set; }
/// <summary>Display name of the client.</summary>
public string Name { get; set; } = string.Empty;
}
/// <summary>Shadow holder for a persisted <see cref="Client"/>.</summary>
public sealed class ClientShadow : Shadow { /* no extra data */ }
/// <summary>
/// Persisted shape of an <see cref="Order"/>: data only. The object graph is
/// flattened for storage — the back-reference to the client becomes a foreign
/// key, because storage has ids, not object references.
/// </summary>
public sealed class OrderData : DbBase
{
/// <summary>Free-text description of what this order is for.</summary>
public string Description { get; set; } = string.Empty;
/// <summary>Shadow holder for a persisted <see cref="Order"/>.</summary>
public sealed class OrderShadow : Shadow { /* no extra data */ }
/// <summary>
/// Foreign key to the owning client: <see cref="Guid.Empty"/> when the
/// order has no client, or when its client had no id yet at save time —
/// save clients before their orders.
/// </summary>
public Guid ClientId { get; set; }
}
/// <summary>
/// The fake <c>DbContext</c>, refactored to use per-type shadow collections
/// (mirroring EF Core's <c>Set&lt;T&gt;</c>) plus an instance-level
/// <c>Find&lt;T&gt;</c> query method.
/// The fake <c>DbContext</c>: per-type tables of data records, mirroring EF
/// Core's <c>Set&lt;T&gt;</c>. <see cref="Save(Client)"/> / <see cref="Save(Order)"/>
/// map the domain object's *current* state into its record — inserting on the
/// first save, refreshing in place on later ones.
/// </summary>
public class DbContext
{
// ── per-type shadow tables ───────────────────────────────────────
private readonly List<ClientShadow> _clients = new();
private readonly List<OrderShadow> _orders = new();
// ── per-type data tables ─────────────────────────────────────────
private readonly List<ClientData> _clients = new();
private readonly List<OrderData> _orders = new();
// ── fast lookup: domain object reference → its shadow ────────────
private readonly Dictionary<object, Shadow> _byRef = new();
// ── fast lookup: domain object reference → its persisted record ──
private readonly Dictionary<object, DbBase> _byRef = new();
// ── exposed per-type tables (read-only view) ────────────────────
public IReadOnlyList<ClientShadow> Clients => _clients.AsReadOnly();
public IReadOnlyList<OrderShadow> Orders => _orders.AsReadOnly();
// ── exposed per-type tables (read-only view) ─────────────────────
public IReadOnlyList<ClientData> Clients => _clients.AsReadOnly();
public IReadOnlyList<OrderData> Orders => _orders.AsReadOnly();
/// <summary>Generic accessor: the strongly-typed "table" for <typeparamref name="T"/>.</summary>
public IReadOnlyList<T> Set<T>() where T : Shadow
public IReadOnlyList<T> Set<T>() where T : DbBase
=> typeof(T) switch
{
var t when t == typeof(ClientShadow) => (IReadOnlyList<T>)_clients.AsReadOnly(),
var t when t == typeof(OrderShadow) => (IReadOnlyList<T>)_orders.AsReadOnly(),
_ => throw new NotSupportedException($"No per-type table for {typeof(T)}"),
var t when t == typeof(ClientData) => (IReadOnlyList<T>)_clients.AsReadOnly(),
var t when t == typeof(OrderData) => (IReadOnlyList<T>)_orders.AsReadOnly(),
_ => throw new NotSupportedException($"No per-type table for {typeof(T)}"),
};
// ── explicit persistence ────────────────────────────────────────
// ── explicit persistence: map + insert, or refresh ───────────────
/// <summary>Persist a <see cref="Client">:</summary>
/// <summary>
/// Persist a <see cref="Client"/>: the first save maps it to a fresh
/// <see cref="ClientData"/> row and writes the generated id back into the
/// domain object; a later save refreshes that row's data in place.
/// </summary>
public void Save(Client client)
{
ArgumentNullException.ThrowIfNull(client);
if (!_byRef.TryAdd(client, new ClientShadow { DbContext = this }))
return; // already saved → id unchanged
var shadow = (ClientShadow)_byRef[client];
var fresh = Mappers.ToClientData(client);
if (_byRef.TryGetValue(client, out var existing))
{
((ClientData)existing).Name = fresh.Name; // refresh, keep row identity
return;
}
var id = Guid.NewGuid();
shadow.Id = client.Id = id; // write-back identity
fresh.Id = client.Id = id; // write-back identity
fresh.DbContext = this;
_clients.Add(fresh);
_byRef[client] = fresh;
}
/// <summary>Persist an <see cref="Order">.</summary>
/// <summary>
/// Persist an <see cref="Order"/> (same insert-or-refresh rule as
/// <see cref="Save(Client)"/>; save its client first so the foreign key
/// can be filled).
/// </summary>
public void Save(Order order)
{
ArgumentNullException.ThrowIfNull(order);
if (!_byRef.TryAdd(order, new OrderShadow { DbContext = this }))
return; // already saved → id unchanged
var shadow = (OrderShadow)_byRef[order];
var id = Guid.NewGuid();
shadow.Id = order.Id = id; // write-back identity
}
/// <summary>Persist every tracked entity (mirrors EF's <c>SaveChanges</c>).</summary>
public int SaveChanges()
{
var count = 0;
foreach (var shadow in _byRef.Values)
var fresh = Mappers.ToOrderData(order);
if (_byRef.TryGetValue(order, out var existing))
{
if (shadow.Id != Guid.Empty) continue; // already had an id
shadow.Id = Guid.NewGuid();
count++;
var row = (OrderData)existing; // refresh, keep row identity
row.Description = fresh.Description;
row.ClientId = fresh.ClientId;
return;
}
return count;
var id = Guid.NewGuid();
fresh.Id = order.Id = id; // write-back identity
fresh.DbContext = this;
_orders.Add(fresh);
_byRef[order] = fresh;
}
// ── query helpers ───────────────────────────────────────────────
/// <summary>Search the per-type table for a shadow whose predicate matches.</summary>
public T? Find<T>(Func<T, bool> predicate) where T : Shadow
/// <summary>Search the per-type table for a record whose predicate matches.</summary>
public T? Find<T>(Func<T, bool> predicate) where T : DbBase
=> Set<T>().FirstOrDefault(predicate);
// ── tracking / status ───────────────────────────────────────────
@@ -97,6 +122,6 @@ public class DbContext
/// <summary>True if <paramref name="entity"/> has been saved through this context.</summary>
public bool IsTracked(object entity) => _byRef.ContainsKey(entity);
/// <summary>All shadow entities this context currently manages.</summary>
public IReadOnlyList<Shadow> Tracked => _byRef.Values.ToList();
/// <summary>All data records this context currently manages.</summary>
public IReadOnlyList<DbBase> Tracked => _byRef.Values.ToList();
}
+40 -4
View File
@@ -1,13 +1,21 @@
namespace After;
/// <summary>
/// Hand-written mappers between the plain domain and the DTOs (no AutoMapper —
/// the mapping code is part of the illustration). Each public method maps in
/// exactly one direction and never mutates its input.
/// Hand-written mappers out of the plain domain (no AutoMapper — the mapping
/// code is part of the illustration). Each public method maps in exactly one
/// direction and never mutates its input. Two families, two destinations:
/// <list type="bullet">
/// <item><see cref="ClientDto"/>/<see cref="OrderDto"/> — transport to the
/// WebApp;</item>
/// <item><see cref="ClientData"/>/<see cref="OrderData"/> — the data-only
/// records the persistence framework stores.</item>
/// </list>
///
/// The <c>Client.Orders</c> / <c>Order.Client</c> back-reference cycle is
/// resolved with a reference-identity cache: the same instance maps to the
/// same DTO (and back), so the graph terminates and stays consistent.
/// same DTO (and back), so the graph terminates and stays consistent. The
/// persistence mapping needs no cache: records reference each other by id,
/// not by object, so the graph is flattened and cannot cycle.
/// </summary>
public static class Mappers
{
@@ -99,4 +107,32 @@ public static class Mappers
seen[dto] = order;
return order;
}
// ------------------------------------------------------------------
// Domain -> persistence (data-only records; graph flattened to ids)
// ------------------------------------------------------------------
/// <summary>Map a <see cref="Client"/> to its persistence record <see cref="ClientData"/>.</summary>
public static ClientData ToClientData(Client client)
{
ArgumentNullException.ThrowIfNull(client);
return new ClientData { Id = client.Id, Name = client.Name };
}
/// <summary>
/// Map an <see cref="Order"/> to its persistence record <see cref="OrderData"/>:
/// the object graph is flattened — <see cref="Order.Client"/> becomes the
/// <see cref="OrderData.ClientId"/> foreign key (empty when the order has
/// no client, or when that client has not been saved yet).
/// </summary>
public static OrderData ToOrderData(Order order)
{
ArgumentNullException.ThrowIfNull(order);
return new OrderData
{
Id = order.Id,
Description = order.Description,
ClientId = order.Client?.Id ?? Guid.Empty,
};
}
}