using Before; // --------------------------------------------------------------------------- // Before.Console — a straight-line demo of the ActiveRecord-style pattern. // // The console app sets DbBase.Context (the shared singleton) once at startup, // then creates client/order entities, saves them through the context, and // queries back using the ActiveRecord entry points: // • Client.FindByName(name) — no context argument: rides the // DbBase.Context singleton // • listing via DbBase.Context!.Tracked // --------------------------------------------------------------------------- var ctx = new DbContext(); DbBase.Context = ctx; // ----- seed data ---------------------------------------------------------- var jane = new Client { Name = "Jane Doe" }; var bob = new Client { Name = "Bob Smith" }; jane.Orders.Add(new Order { Description = "Design consultation", TotalInCents = 120_00 }); jane.Orders.Add(new Order { Description = "Website redesign", TotalInCents = 750_00 }); bob.Orders.Add(new Order { Description = "Monthly retainer", TotalInCents = 85_00 }); // Orders need to be attached too so they get IDs: ctx.Attach(jane.Orders[0]); ctx.Attach(jane.Orders[1]); ctx.Attach(bob.Orders[0]); ctx.Attach(jane); ctx.Attach(bob); ctx.Save(); // ----- list all clients --------------------------------------------------- Console.WriteLine("=== All Clients ==="); foreach (var client in DbBase.Context!.Tracked.OfType()) { Console.WriteLine($"{client.Name} [{client.Id}]"); foreach (var order in client.Orders) Console.WriteLine($" - order [{order.Id}]: {order.Description} ({order.TotalInCents} cents)"); } // ----- find by name ------------------------------------------------------- Console.WriteLine("\n=== Find by Name (null-returning) ==="); // No context argument: FindByName falls back to the DbBase.Context singleton. var found = Client.FindByName("Jane Doe"); if (found is not null) { Console.WriteLine($"Found: {found.Name} [{found.Id}]"); Console.WriteLine($" Orders: {found.Orders.Count}"); } else { Console.WriteLine("Not found."); } // ----- find by name (throwing variant) ------------------------------------ Console.WriteLine("\n=== Find by Name Required (throws instead of returning null) ==="); try { var required = Client.FindByNameRequired("Jane Doe"); Console.WriteLine($"Found: {required.Name} [{required.Id}]"); Console.WriteLine($" Orders: {required.Orders.Count}"); } catch (ObjectNotFoundException ex) { Console.WriteLine($"Not found: {ex.Message}"); } // Show the contrast with a non-existent name: Console.WriteLine("\n=== Miss: null-returning vs throwing ==="); var missNull = Client.FindByName("Nobody Here"); Console.WriteLine($"FindByName(\"Nobody Here\"): {(missNull == null ? "null" : missNull.Name)}"); try { Client.FindByNameRequired("Nobody Here"); } catch (ObjectNotFoundException ex) { var msg = ex.Message.ReplaceLineEndings(" ").Trim(); Console.WriteLine($"FindByNameRequired(\"Nobody Here\"): throws - {msg}"); }