Bundle: redb / redb.Examples (redb.Examples.txt), 385 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt ==== Path: redb/redb.Examples/Ef/CommandCounters.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/CommandCounters.cs ---- using System.Data.Common; using System.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics; using redb.Core.Diagnostics; namespace redb.Examples.Ef; /// /// Counts database round trips on both sides of the comparison, so the table can show how many commands /// each library sent for the same task. The runner reads the counter before and after an example. /// internal static class CommandCounters { private static long _redb; private static long _ef; private static ActivityListener? _redbListener; /// Commands redb has sent so far. public static long Redb => Interlocked.Read(ref _redb); /// Commands EF Core has sent so far. public static long Ef => Interlocked.Read(ref _ef); /// /// Starts counting redb commands. redb declares every database command as an activity on /// ; the listener only counts them and asks for no tags. /// public static void StartRedb() { if (_redbListener != null) return; _redbListener = new ActivityListener { ShouldListenTo = source => source.Name == RedbActivitySource.SourceName, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.PropagationData, ActivityStarted = _ => Interlocked.Increment(ref _redb) }; ActivitySource.AddActivityListener(_redbListener); } /// Interceptor that counts every command EF Core executes; one instance for all contexts. public static readonly DbCommandInterceptor EfInterceptor = new EfCommandCounter(); private sealed class EfCommandCounter : DbCommandInterceptor { public override InterceptionResult ReaderExecuting( DbCommand command, CommandEventData eventData, InterceptionResult result) { Interlocked.Increment(ref _ef); return result; } public override ValueTask> ReaderExecutingAsync( DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { Interlocked.Increment(ref _ef); return ValueTask.FromResult(result); } public override InterceptionResult ScalarExecuting( DbCommand command, CommandEventData eventData, InterceptionResult result) { Interlocked.Increment(ref _ef); return result; } public override ValueTask> ScalarExecutingAsync( DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { Interlocked.Increment(ref _ef); return ValueTask.FromResult(result); } public override InterceptionResult NonQueryExecuting( DbCommand command, CommandEventData eventData, InterceptionResult result) { Interlocked.Increment(ref _ef); return result; } public override ValueTask> NonQueryExecutingAsync( DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { Interlocked.Increment(ref _ef); return ValueTask.FromResult(result); } } } Path: redb/redb.Examples/Ef/DepartmentEfMapping.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/DepartmentEfMapping.cs ---- using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef.Entities; using Biz = redb.Examples.Models; namespace redb.Examples.Ef; /// /// The department tree of the examples through EF Core: a node is a header row in objects (its parent in /// _id_parent) with a DepartmentProps row, turned into the redb /// hands out. EF has no recursive query and no depth parameter, so its twins cover the operations on one level: /// create, delete, move, count, roots, leaves and direct children. /// internal static class DepartmentEfMapping { /// A new node under (a root when null). Keys come from the database. public static objects ToEntity(string name, string code, string description, decimal budget, objects? parent) { var now = DateTime.UtcNow; return new objects { _id_scheme = EfSchemeIds.Department, _id_owner = 0, _id_who_change = 0, _date_create = now, _date_modify = now, _name = name, _id_parentNavigation = parent, DepartmentProps = new DepartmentProps { Name = name, Code = code, Description = description, Budget = budget, IsActive = true } }; } /// Every department node with its header, as a query. public static IQueryable Nodes(this FlatContext db) => db.DepartmentProps.Include(d => d.objects); /// The business object of a loaded department node, without parent or children. public static TreeRedbObject ToBusiness(DepartmentProps d) { var h = d.objects; return new TreeRedbObject { id = h._id, parent_id = h._id_parent, scheme_id = h._id_scheme, owner_id = h._id_owner, who_change_id = h._id_who_change, date_create = h._date_create, date_modify = h._date_modify, date_begin = h._date_begin, date_complete = h._date_complete, key = h._key, name = h._name, note = h._note, value_long = h._value_long, value_string = h._value_string, value_guid = h._value_guid, value_bool = h._value_bool, value_double = h._value_double, value_numeric = h._value_numeric, value_datetime = h._value_datetime, value_bytes = h._value_bytes, Props = new Biz.DepartmentProps { Name = d.Name ?? string.Empty, Code = d.Code ?? string.Empty, Description = d.Description ?? string.Empty, IsActive = d.IsActive ?? false, Budget = d.Budget ?? 0m } }; } } Path: redb/redb.Examples/Ef/EfSchemeIds.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/EfSchemeIds.cs ---- namespace redb.Examples.Ef; /// /// Values written to objects._id_scheme by the EF twins. An EF application has no redb schemes, but /// the column needs a value; a fixed one per Props type keeps rows of different types apart in the shared /// header table. A header without Props (a plain object) gets . /// internal static class EfSchemeIds { public const long None = 0; public const long Employee = 1; public const long ProjectMetrics = 2; public const long Department = 3; public const long City = 4; public const long Person = 5; } Path: redb/redb.Examples/Ef/EmployeeEfGraph.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/EmployeeEfGraph.cs ---- using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef.Entities; using Biz = redb.Examples.Models; namespace redb.Examples.Ef; /// /// Reading an employee through EF Core as redb hands it out: the whole object, header and every nested /// class, array and dictionary, turned into of the business class. /// internal static class EmployeeEfGraph { /// /// The query with every part of the employee included. Split into one SQL statement per collection: /// a single statement would multiply the rows of independent collections (skills times contacts /// times offices and so on). /// public static IQueryable WithGraph(this IQueryable query) => query .Include(e => e.objects) .Include(e => e.EmployeeProps_Skills) .Include(e => e.EmployeeProps_SkillLevels) .Include(e => e.EmployeeProps_Certifications) .Include(e => e.EmployeeProps_CertificationYears) .Include(e => e.EmployeeProps_PastProjects) .Include(e => e.EmployeeProps_HomeAddress!).ThenInclude(a => a.EmployeeProps_HomeAddress_Building!).ThenInclude(b => b.EmployeeProps_HomeAddress_Building_Amenities) .Include(e => e.EmployeeProps_HomeAddress!).ThenInclude(a => a.EmployeeProps_HomeAddress_Building!).ThenInclude(b => b.EmployeeProps_HomeAddress_Building_AccessCodes) .Include(e => e.EmployeeProps_HomeAddress!).ThenInclude(a => a.EmployeeProps_HomeAddress_Building!).ThenInclude(b => b.EmployeeProps_HomeAddress_Building_ParkingSpots) .Include(e => e.EmployeeProps_HomeAddress!).ThenInclude(a => a.EmployeeProps_HomeAddress_Building!).ThenInclude(b => b.EmployeeProps_HomeAddress_Building_ElevatorFloors) .Include(e => e.EmployeeProps_WorkAddress!).ThenInclude(a => a.EmployeeProps_WorkAddress_Building!).ThenInclude(b => b.EmployeeProps_WorkAddress_Building_Amenities) .Include(e => e.EmployeeProps_WorkAddress!).ThenInclude(a => a.EmployeeProps_WorkAddress_Building!).ThenInclude(b => b.EmployeeProps_WorkAddress_Building_AccessCodes) .Include(e => e.EmployeeProps_WorkAddress!).ThenInclude(a => a.EmployeeProps_WorkAddress_Building!).ThenInclude(b => b.EmployeeProps_WorkAddress_Building_ParkingSpots) .Include(e => e.EmployeeProps_WorkAddress!).ThenInclude(a => a.EmployeeProps_WorkAddress_Building!).ThenInclude(b => b.EmployeeProps_WorkAddress_Building_ElevatorFloors) .Include(e => e.EmployeeProps_EmergencyAddress!).ThenInclude(a => a.EmployeeProps_EmergencyAddress_Building!).ThenInclude(b => b.EmployeeProps_EmergencyAddress_Building_Amenities) .Include(e => e.EmployeeProps_EmergencyAddress!).ThenInclude(a => a.EmployeeProps_EmergencyAddress_Building!).ThenInclude(b => b.EmployeeProps_EmergencyAddress_Building_AccessCodes) .Include(e => e.EmployeeProps_EmergencyAddress!).ThenInclude(a => a.EmployeeProps_EmergencyAddress_Building!).ThenInclude(b => b.EmployeeProps_EmergencyAddress_Building_ParkingSpots) .Include(e => e.EmployeeProps_EmergencyAddress!).ThenInclude(a => a.EmployeeProps_EmergencyAddress_Building!).ThenInclude(b => b.EmployeeProps_EmergencyAddress_Building_ElevatorFloors) .Include(e => e.EmployeeProps_Contacts).ThenInclude(c => c.EmployeeProps_Contacts_NotificationHours) .Include(e => e.EmployeeProps_Contacts).ThenInclude(c => c.EmployeeProps_Contacts_Metadata) .Include(e => e.EmployeeProps_PhoneDirectory) .Include(e => e.EmployeeProps_BonusByYear) .Include(e => e.EmployeeProps_ProjectMetrics) .Include(e => e.EmployeeProps_PerformanceReviews) .Include(e => e.EmployeeProps_OfficeLocations).ThenInclude(o => o.EmployeeProps_OfficeLocations_Building!).ThenInclude(b => b.EmployeeProps_OfficeLocations_Building_Amenities) .Include(e => e.EmployeeProps_OfficeLocations).ThenInclude(o => o.EmployeeProps_OfficeLocations_Building!).ThenInclude(b => b.EmployeeProps_OfficeLocations_Building_AccessCodes) .Include(e => e.EmployeeProps_OfficeLocations).ThenInclude(o => o.EmployeeProps_OfficeLocations_Building!).ThenInclude(b => b.EmployeeProps_OfficeLocations_Building_ParkingSpots) .Include(e => e.EmployeeProps_OfficeLocations).ThenInclude(o => o.EmployeeProps_OfficeLocations_Building!).ThenInclude(b => b.EmployeeProps_OfficeLocations_Building_ElevatorFloors) .Include(e => e.EmployeeProps_DepartmentHistory).ThenInclude(d => d.EmployeeProps_DepartmentHistory_Projects) .Include(e => e.EmployeeProps_DepartmentHistory).ThenInclude(d => d.EmployeeProps_DepartmentHistory_Leaders) .Include(e => e.EmployeeProps_DepartmentHistory).ThenInclude(d => d.EmployeeProps_DepartmentHistory_BudgetByYear) .AsSplitQuery(); /// Runs the query and turns every employee into the business object. public static async Task>> ToBusinessListAsync(this IQueryable query) => (await query.ToListAsync()).Select(ToBusiness).ToList(); /// /// The business object of a loaded employee, as redb returns it. References to other objects /// (RedbObject<ProjectMetricsProps>) carry the target id only: the seeded data has none, /// and loading their targets would be one more include chain. /// public static RedbObject ToBusiness(EmployeeProps e) { var h = e.objects; return new RedbObject { id = h._id, parent_id = h._id_parent, scheme_id = h._id_scheme, owner_id = h._id_owner, who_change_id = h._id_who_change, date_create = h._date_create, date_modify = h._date_modify, date_begin = h._date_begin, date_complete = h._date_complete, key = h._key, name = h._name, note = h._note, value_long = h._value_long, value_string = h._value_string, value_guid = h._value_guid, value_bool = h._value_bool, value_double = h._value_double, value_numeric = h._value_numeric, value_datetime = h._value_datetime, value_bytes = h._value_bytes, Props = new Biz.EmployeeProps { FirstName = e.FirstName ?? string.Empty, LastName = e.LastName ?? string.Empty, Age = e.Age ?? 0, HireDate = e.HireDate ?? default, Position = e.Position ?? string.Empty, Salary = e.Salary ?? 0m, Department = e.Department ?? string.Empty, EmployeeCode = e.EmployeeCode, Skills = Elements(e.EmployeeProps_Skills, x => x._idx, x => x._value!), SkillLevels = Elements(e.EmployeeProps_SkillLevels, x => x._idx, x => x._value ?? 0), Certifications = Elements(e.EmployeeProps_Certifications, x => x._idx, x => x._value!), CertificationYears = Elements(e.EmployeeProps_CertificationYears, x => x._idx, x => x._value ?? 0), HomeAddress = e.EmployeeProps_HomeAddress is not { } home ? null : Address(home.City, home.Street, home.EmployeeProps_HomeAddress_Building is not { } b ? null : Building(b.Floor, b.Name, Elements(b.EmployeeProps_HomeAddress_Building_Amenities, x => x._idx, x => x._value!), Elements(b.EmployeeProps_HomeAddress_Building_AccessCodes, x => x._idx, x => x._value ?? 0), Elements(b.EmployeeProps_HomeAddress_Building_ParkingSpots, x => x._idx, x => x._value!), Elements(b.EmployeeProps_HomeAddress_Building_ElevatorFloors, x => x._idx, x => x._value ?? 0))), WorkAddress = e.EmployeeProps_WorkAddress is not { } work ? null : Address(work.City, work.Street, work.EmployeeProps_WorkAddress_Building is not { } wb ? null : Building(wb.Floor, wb.Name, Elements(wb.EmployeeProps_WorkAddress_Building_Amenities, x => x._idx, x => x._value!), Elements(wb.EmployeeProps_WorkAddress_Building_AccessCodes, x => x._idx, x => x._value ?? 0), Elements(wb.EmployeeProps_WorkAddress_Building_ParkingSpots, x => x._idx, x => x._value!), Elements(wb.EmployeeProps_WorkAddress_Building_ElevatorFloors, x => x._idx, x => x._value ?? 0))), EmergencyAddress = e.EmployeeProps_EmergencyAddress is not { } emergency ? null : Address(emergency.City, emergency.Street, emergency.EmployeeProps_EmergencyAddress_Building is not { } eb ? null : Building(eb.Floor, eb.Name, Elements(eb.EmployeeProps_EmergencyAddress_Building_Amenities, x => x._idx, x => x._value!), Elements(eb.EmployeeProps_EmergencyAddress_Building_AccessCodes, x => x._idx, x => x._value ?? 0), Elements(eb.EmployeeProps_EmergencyAddress_Building_ParkingSpots, x => x._idx, x => x._value!), Elements(eb.EmployeeProps_EmergencyAddress_Building_ElevatorFloors, x => x._idx, x => x._value ?? 0))), Contacts = Elements(e.EmployeeProps_Contacts, x => x._idx, c => new Biz.Contact { Type = c.Type ?? string.Empty, Value = c.Value ?? string.Empty, IsVerified = c.IsVerified ?? false, NotificationHours = Elements(c.EmployeeProps_Contacts_NotificationHours, x => x._idx, x => x._value ?? 0), Metadata = Elements(c.EmployeeProps_Contacts_Metadata, x => x._idx, m => new Biz.ContactDetail { Label = m.Label ?? string.Empty, Value = m.Value ?? string.Empty }) }), CurrentProject = e.CurrentProject is { } projectId ? new RedbObject { id = projectId } : null, PastProjects = Elements(e.EmployeeProps_PastProjects, x => x._idx, x => new RedbObject { id = x._value ?? 0 }), PhoneDirectory = Entries(e.EmployeeProps_PhoneDirectory, x => x._key, x => x._value!), BonusByYear = Entries(e.EmployeeProps_BonusByYear, x => x._key, x => x._value ?? 0m), ProjectMetrics = Entries(e.EmployeeProps_ProjectMetrics, x => x._key, x => new RedbObject { id = x._value ?? 0 }), PerformanceReviews = Entries(e.EmployeeProps_PerformanceReviews, x => (x._key_Item1, x._key_Item2), x => x._value!), OfficeLocations = Entries(e.EmployeeProps_OfficeLocations, x => x._key, o => Address(o.City, o.Street, o.EmployeeProps_OfficeLocations_Building is not { } ob ? null : Building(ob.Floor, ob.Name, Elements(ob.EmployeeProps_OfficeLocations_Building_Amenities, x => x._idx, x => x._value!), Elements(ob.EmployeeProps_OfficeLocations_Building_AccessCodes, x => x._idx, x => x._value ?? 0), Elements(ob.EmployeeProps_OfficeLocations_Building_ParkingSpots, x => x._idx, x => x._value!), Elements(ob.EmployeeProps_OfficeLocations_Building_ElevatorFloors, x => x._idx, x => x._value ?? 0)))), DepartmentHistory = Entries(e.EmployeeProps_DepartmentHistory, x => x._key, d => new Biz.Department { Name = d.Name ?? string.Empty, HeadCount = d.HeadCount ?? 0, Projects = Elements(d.EmployeeProps_DepartmentHistory_Projects, x => x._idx, x => x._value!) ?? [], Leaders = Elements(d.EmployeeProps_DepartmentHistory_Leaders, x => x._idx, t => new Biz.Tag { Name = t.Name ?? string.Empty, Priority = t.Priority ?? 0, Description = t.Description }) ?? [], BudgetByYear = Entries(d.EmployeeProps_DepartmentHistory_BudgetByYear, x => x._key, x => x._value ?? 0) }) } }; } private static Biz.Address Address(string? city, string? street, Biz.BuildingInfo? building) => new() { City = city ?? string.Empty, Street = street ?? string.Empty, Building = building }; private static Biz.BuildingInfo Building(int? floor, string? name, string[]? amenities, int[]? accessCodes, string[]? parkingSpots, int[]? elevatorFloors) => new() { Floor = floor ?? 0, Name = name ?? string.Empty, Amenities = amenities, AccessCodes = accessCodes, ParkingSpots = parkingSpots, ElevatorFloors = elevatorFloors }; /// /// The array of a collection table in element order. No rows read as null: the flat model cannot tell /// an empty array from a missing one, and redb leaves a missing array null. /// private static TValue[]? Elements(ICollection rows, Func index, Func value) => rows.Count == 0 ? null : rows.OrderBy(index).Select(value).ToArray(); /// The dictionary of a collection table; no rows read as null, as with arrays. private static Dictionary? Entries(ICollection rows, Func key, Func value) where TKey : notnull => rows.Count == 0 ? null : rows.ToDictionary(key, value); } Path: redb/redb.Examples/Ef/EmployeeEfMapping.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/EmployeeEfMapping.cs ---- using redb.Core.Models.Entities; using redb.Examples.Ef.Entities; using Biz = redb.Examples.Models; namespace redb.Examples.Ef; /// /// Turns the business class into the EF entity graph of the flat tables. /// /// This is the code an EF application writes by hand to get its business class in and out of the /// database: one entity per flat table, a list per array and dictionary, a reference per nested class. /// redb does the same from the Props class alone. The mapping is part of every EF measurement. /// /// internal static class EmployeeEfMapping { /// /// The header row of a new employee with its Props attached. Keys are left unset: the database hands /// them out from the flat sequence, and EF copies the header key into the Props row. /// public static objects ToEntity(RedbObject source) { var props = source.Props ?? throw new ArgumentException("An employee without Props.", nameof(source)); var now = DateTime.UtcNow; return new objects { _id_scheme = EfSchemeIds.Employee, // The system user, as redb writes it for objects saved without a user (owner_id 0). _id_owner = 0, _id_who_change = 0, _date_create = now, _date_modify = now, _name = source.Name, EmployeeProps = ToEntity(props) }; } private static EmployeeProps ToEntity(Biz.EmployeeProps p) => new() { FirstName = p.FirstName, LastName = p.LastName, Age = p.Age, // The reading redb stores: the clock value marked UTC (DateTimeConverter.NormalizeForStorage). HireDate = DateTime.SpecifyKind(p.HireDate, DateTimeKind.Utc), Position = p.Position, Salary = p.Salary, Department = p.Department, EmployeeCode = p.EmployeeCode, CurrentProject = p.CurrentProject?.Id, EmployeeProps_Skills = Items(p.Skills, (i, v) => new EmployeeProps_Skills { _idx = i, _value = v }), EmployeeProps_SkillLevels = Items(p.SkillLevels, (i, v) => new EmployeeProps_SkillLevels { _idx = i, _value = v }), EmployeeProps_Certifications = Items(p.Certifications, (i, v) => new EmployeeProps_Certifications { _idx = i, _value = v }), EmployeeProps_CertificationYears = Items(p.CertificationYears, (i, v) => new EmployeeProps_CertificationYears { _idx = i, _value = v }), EmployeeProps_HomeAddress = HomeAddress(p.HomeAddress), EmployeeProps_WorkAddress = WorkAddress(p.WorkAddress), EmployeeProps_EmergencyAddress = EmergencyAddress(p.EmergencyAddress), EmployeeProps_Contacts = Items(p.Contacts, (i, c) => new EmployeeProps_Contacts { _idx = i, Type = c.Type, Value = c.Value, IsVerified = c.IsVerified, EmployeeProps_Contacts_NotificationHours = Items(c.NotificationHours, (j, v) => new EmployeeProps_Contacts_NotificationHours { _idx = j, _value = v }), EmployeeProps_Contacts_Metadata = Items(c.Metadata, (j, m) => new EmployeeProps_Contacts_Metadata { _idx = j, Label = m.Label, Value = m.Value }) }), EmployeeProps_PastProjects = Items(p.PastProjects, (i, o) => new EmployeeProps_PastProjects { _idx = i, _value = o?.Id }), EmployeeProps_PhoneDirectory = Entries(p.PhoneDirectory, (k, v) => new EmployeeProps_PhoneDirectory { _key = k, _value = v }), EmployeeProps_BonusByYear = Entries(p.BonusByYear, (k, v) => new EmployeeProps_BonusByYear { _key = k, _value = v }), EmployeeProps_ProjectMetrics = Entries(p.ProjectMetrics, (k, o) => new EmployeeProps_ProjectMetrics { _key = k, _value = o?.Id }), EmployeeProps_PerformanceReviews = Entries(p.PerformanceReviews, (k, v) => new EmployeeProps_PerformanceReviews { _key_Item1 = k.Year, _key_Item2 = k.Quarter, _value = v }), EmployeeProps_OfficeLocations = Entries(p.OfficeLocations, (k, a) => new EmployeeProps_OfficeLocations { _key = k, City = a?.City, Street = a?.Street, EmployeeProps_OfficeLocations_Building = OfficeBuilding(a?.Building) }), EmployeeProps_DepartmentHistory = Entries(p.DepartmentHistory, (k, d) => new EmployeeProps_DepartmentHistory { _key = k, Name = d?.Name, HeadCount = d?.HeadCount, EmployeeProps_DepartmentHistory_Projects = Items(d?.Projects, (i, v) => new EmployeeProps_DepartmentHistory_Projects { _idx = i, _value = v }), EmployeeProps_DepartmentHistory_Leaders = Items(d?.Leaders, (i, t) => new EmployeeProps_DepartmentHistory_Leaders { _idx = i, Name = t.Name, Priority = t.Priority, Description = t.Description }), EmployeeProps_DepartmentHistory_BudgetByYear = Entries(d?.BudgetByYear, (y, v) => new EmployeeProps_DepartmentHistory_BudgetByYear { _key = y, _value = v }) }) }; // Every place an Address appears is a table of its own in the flat model, so each one needs its own // copy of the same code. private static EmployeeProps_HomeAddress? HomeAddress(Biz.Address? a) => a == null ? null : new() { City = a.City, Street = a.Street, EmployeeProps_HomeAddress_Building = a.Building is not { } b ? null : new() { Floor = b.Floor, Name = b.Name, EmployeeProps_HomeAddress_Building_Amenities = Items(b.Amenities, (i, v) => new EmployeeProps_HomeAddress_Building_Amenities { _idx = i, _value = v }), EmployeeProps_HomeAddress_Building_AccessCodes = Items(b.AccessCodes, (i, v) => new EmployeeProps_HomeAddress_Building_AccessCodes { _idx = i, _value = v }), EmployeeProps_HomeAddress_Building_ParkingSpots = Items(b.ParkingSpots, (i, v) => new EmployeeProps_HomeAddress_Building_ParkingSpots { _idx = i, _value = v }), EmployeeProps_HomeAddress_Building_ElevatorFloors = Items(b.ElevatorFloors, (i, v) => new EmployeeProps_HomeAddress_Building_ElevatorFloors { _idx = i, _value = v }) } }; private static EmployeeProps_WorkAddress? WorkAddress(Biz.Address? a) => a == null ? null : new() { City = a.City, Street = a.Street, EmployeeProps_WorkAddress_Building = a.Building is not { } b ? null : new() { Floor = b.Floor, Name = b.Name, EmployeeProps_WorkAddress_Building_Amenities = Items(b.Amenities, (i, v) => new EmployeeProps_WorkAddress_Building_Amenities { _idx = i, _value = v }), EmployeeProps_WorkAddress_Building_AccessCodes = Items(b.AccessCodes, (i, v) => new EmployeeProps_WorkAddress_Building_AccessCodes { _idx = i, _value = v }), EmployeeProps_WorkAddress_Building_ParkingSpots = Items(b.ParkingSpots, (i, v) => new EmployeeProps_WorkAddress_Building_ParkingSpots { _idx = i, _value = v }), EmployeeProps_WorkAddress_Building_ElevatorFloors = Items(b.ElevatorFloors, (i, v) => new EmployeeProps_WorkAddress_Building_ElevatorFloors { _idx = i, _value = v }) } }; private static EmployeeProps_EmergencyAddress? EmergencyAddress(Biz.Address? a) => a == null ? null : new() { City = a.City, Street = a.Street, EmployeeProps_EmergencyAddress_Building = a.Building is not { } b ? null : new() { Floor = b.Floor, Name = b.Name, EmployeeProps_EmergencyAddress_Building_Amenities = Items(b.Amenities, (i, v) => new EmployeeProps_EmergencyAddress_Building_Amenities { _idx = i, _value = v }), EmployeeProps_EmergencyAddress_Building_AccessCodes = Items(b.AccessCodes, (i, v) => new EmployeeProps_EmergencyAddress_Building_AccessCodes { _idx = i, _value = v }), EmployeeProps_EmergencyAddress_Building_ParkingSpots = Items(b.ParkingSpots, (i, v) => new EmployeeProps_EmergencyAddress_Building_ParkingSpots { _idx = i, _value = v }), EmployeeProps_EmergencyAddress_Building_ElevatorFloors = Items(b.ElevatorFloors, (i, v) => new EmployeeProps_EmergencyAddress_Building_ElevatorFloors { _idx = i, _value = v }) } }; private static EmployeeProps_OfficeLocations_Building? OfficeBuilding(Biz.BuildingInfo? b) => b == null ? null : new() { Floor = b.Floor, Name = b.Name, EmployeeProps_OfficeLocations_Building_Amenities = Items(b.Amenities, (i, v) => new EmployeeProps_OfficeLocations_Building_Amenities { _idx = i, _value = v }), EmployeeProps_OfficeLocations_Building_AccessCodes = Items(b.AccessCodes, (i, v) => new EmployeeProps_OfficeLocations_Building_AccessCodes { _idx = i, _value = v }), EmployeeProps_OfficeLocations_Building_ParkingSpots = Items(b.ParkingSpots, (i, v) => new EmployeeProps_OfficeLocations_Building_ParkingSpots { _idx = i, _value = v }), EmployeeProps_OfficeLocations_Building_ElevatorFloors = Items(b.ElevatorFloors, (i, v) => new EmployeeProps_OfficeLocations_Building_ElevatorFloors { _idx = i, _value = v }) }; /// One row per array element, its position in _idx; no rows for a null array. private static List Items(IEnumerable? values, Func make) => values?.Select((value, index) => make(index, value)).ToList() ?? []; /// One row per dictionary entry; no rows for a null dictionary. private static List Entries(IDictionary? values, Func make) where TKey : notnull => values?.Select(entry => make(entry.Key, entry.Value)).ToList() ?? []; } Path: redb/redb.Examples/Ef/Entities/CityProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/CityProps.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class CityProps { public long _id { get; set; } public string? Name { get; set; } public int? Population { get; set; } public string? Region { get; set; } public bool? IsCapital { get; set; } public virtual ICollection CityProps_Coordinates { get; set; } = new List(); public virtual objects objects { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/CityProps_Coordinates.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/CityProps_Coordinates.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class CityProps_Coordinates { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public double? _value { get; set; } public virtual CityProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/DepartmentProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/DepartmentProps.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class DepartmentProps { public long _id { get; set; } public string? Name { get; set; } public string? Description { get; set; } public bool? IsActive { get; set; } public decimal? Budget { get; set; } public string? Code { get; set; } public virtual objects objects { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps { public long _id { get; set; } public string? FirstName { get; set; } public string? LastName { get; set; } public int? Age { get; set; } public DateTime? HireDate { get; set; } public string? Position { get; set; } public decimal? Salary { get; set; } public string? Department { get; set; } public string? EmployeeCode { get; set; } public long? CurrentProject { get; set; } public virtual ProjectMetricsProps? CurrentProjectNavigation { get; set; } public virtual ICollection EmployeeProps_BonusByYear { get; set; } = new List(); public virtual ICollection EmployeeProps_CertificationYears { get; set; } = new List(); public virtual ICollection EmployeeProps_Certifications { get; set; } = new List(); public virtual ICollection EmployeeProps_Contacts { get; set; } = new List(); public virtual ICollection EmployeeProps_DepartmentHistory { get; set; } = new List(); public virtual EmployeeProps_EmergencyAddress? EmployeeProps_EmergencyAddress { get; set; } public virtual EmployeeProps_HomeAddress? EmployeeProps_HomeAddress { get; set; } public virtual ICollection EmployeeProps_OfficeLocations { get; set; } = new List(); public virtual ICollection EmployeeProps_PastProjects { get; set; } = new List(); public virtual ICollection EmployeeProps_PerformanceReviews { get; set; } = new List(); public virtual ICollection EmployeeProps_PhoneDirectory { get; set; } = new List(); public virtual ICollection EmployeeProps_ProjectMetrics { get; set; } = new List(); public virtual ICollection EmployeeProps_SkillLevels { get; set; } = new List(); public virtual ICollection EmployeeProps_Skills { get; set; } = new List(); public virtual EmployeeProps_WorkAddress? EmployeeProps_WorkAddress { get; set; } public virtual objects objects { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_BonusByYear.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_BonusByYear.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_BonusByYear { public long _id { get; set; } public long _owner_id { get; set; } public int _key { get; set; } public decimal? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_CertificationYears.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_CertificationYears.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_CertificationYears { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_Certifications.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_Certifications.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_Certifications { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_Contacts.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_Contacts.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_Contacts { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? Type { get; set; } public string? Value { get; set; } public bool? IsVerified { get; set; } public virtual ICollection EmployeeProps_Contacts_Metadata { get; set; } = new List(); public virtual ICollection EmployeeProps_Contacts_NotificationHours { get; set; } = new List(); public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_Contacts_Metadata.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_Contacts_Metadata.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_Contacts_Metadata { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? Label { get; set; } public string? Value { get; set; } public virtual EmployeeProps_Contacts _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_Contacts_NotificationHours.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_Contacts_NotificationHours.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_Contacts_NotificationHours { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_Contacts _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_DepartmentHistory { public long _id { get; set; } public long _owner_id { get; set; } public string _key { get; set; } = null!; public string? Name { get; set; } public int? HeadCount { get; set; } public virtual ICollection EmployeeProps_DepartmentHistory_BudgetByYear { get; set; } = new List(); public virtual ICollection EmployeeProps_DepartmentHistory_Leaders { get; set; } = new List(); public virtual ICollection EmployeeProps_DepartmentHistory_Projects { get; set; } = new List(); public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory_BudgetByYear.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory_BudgetByYear.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_DepartmentHistory_BudgetByYear { public long _id { get; set; } public long _owner_id { get; set; } public string _key { get; set; } = null!; public int? _value { get; set; } public virtual EmployeeProps_DepartmentHistory _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory_Leaders.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory_Leaders.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_DepartmentHistory_Leaders { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? Name { get; set; } public int? Priority { get; set; } public string? Description { get; set; } public virtual EmployeeProps_DepartmentHistory _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory_Projects.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_DepartmentHistory_Projects.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_DepartmentHistory_Projects { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_DepartmentHistory _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_EmergencyAddress { public long _id { get; set; } public long _owner_id { get; set; } public string? City { get; set; } public string? Street { get; set; } public virtual EmployeeProps_EmergencyAddress_Building? EmployeeProps_EmergencyAddress_Building { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_EmergencyAddress_Building { public long _id { get; set; } public long _owner_id { get; set; } public int? Floor { get; set; } public string? Name { get; set; } public virtual ICollection EmployeeProps_EmergencyAddress_Building_AccessCodes { get; set; } = new List(); public virtual ICollection EmployeeProps_EmergencyAddress_Building_Amenities { get; set; } = new List(); public virtual ICollection EmployeeProps_EmergencyAddress_Building_ElevatorFloors { get; set; } = new List(); public virtual ICollection EmployeeProps_EmergencyAddress_Building_ParkingSpots { get; set; } = new List(); public virtual EmployeeProps_EmergencyAddress _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_AccessCodes.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_AccessCodes.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_EmergencyAddress_Building_AccessCodes { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_EmergencyAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_Amenities.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_Amenities.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_EmergencyAddress_Building_Amenities { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_EmergencyAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_ElevatorFloors.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_ElevatorFloors.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_EmergencyAddress_Building_ElevatorFloors { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_EmergencyAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_ParkingSpots.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_EmergencyAddress_Building_ParkingSpots.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_EmergencyAddress_Building_ParkingSpots { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_EmergencyAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_HomeAddress { public long _id { get; set; } public long _owner_id { get; set; } public string? City { get; set; } public string? Street { get; set; } public virtual EmployeeProps_HomeAddress_Building? EmployeeProps_HomeAddress_Building { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_HomeAddress_Building { public long _id { get; set; } public long _owner_id { get; set; } public int? Floor { get; set; } public string? Name { get; set; } public virtual ICollection EmployeeProps_HomeAddress_Building_AccessCodes { get; set; } = new List(); public virtual ICollection EmployeeProps_HomeAddress_Building_Amenities { get; set; } = new List(); public virtual ICollection EmployeeProps_HomeAddress_Building_ElevatorFloors { get; set; } = new List(); public virtual ICollection EmployeeProps_HomeAddress_Building_ParkingSpots { get; set; } = new List(); public virtual EmployeeProps_HomeAddress _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_AccessCodes.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_AccessCodes.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_HomeAddress_Building_AccessCodes { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_HomeAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_Amenities.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_Amenities.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_HomeAddress_Building_Amenities { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_HomeAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_ElevatorFloors.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_ElevatorFloors.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_HomeAddress_Building_ElevatorFloors { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_HomeAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_ParkingSpots.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_HomeAddress_Building_ParkingSpots.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_HomeAddress_Building_ParkingSpots { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_HomeAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_OfficeLocations { public long _id { get; set; } public long _owner_id { get; set; } public string _key { get; set; } = null!; public string? City { get; set; } public string? Street { get; set; } public virtual EmployeeProps_OfficeLocations_Building? EmployeeProps_OfficeLocations_Building { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_OfficeLocations_Building { public long _id { get; set; } public long _owner_id { get; set; } public int? Floor { get; set; } public string? Name { get; set; } public virtual ICollection EmployeeProps_OfficeLocations_Building_AccessCodes { get; set; } = new List(); public virtual ICollection EmployeeProps_OfficeLocations_Building_Amenities { get; set; } = new List(); public virtual ICollection EmployeeProps_OfficeLocations_Building_ElevatorFloors { get; set; } = new List(); public virtual ICollection EmployeeProps_OfficeLocations_Building_ParkingSpots { get; set; } = new List(); public virtual EmployeeProps_OfficeLocations _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_AccessCodes.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_AccessCodes.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_OfficeLocations_Building_AccessCodes { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_OfficeLocations_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_Amenities.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_Amenities.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_OfficeLocations_Building_Amenities { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_OfficeLocations_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_ElevatorFloors.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_ElevatorFloors.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_OfficeLocations_Building_ElevatorFloors { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_OfficeLocations_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_ParkingSpots.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_OfficeLocations_Building_ParkingSpots.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_OfficeLocations_Building_ParkingSpots { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_OfficeLocations_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_PastProjects.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_PastProjects.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_PastProjects { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public long? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; public virtual ProjectMetricsProps? _valueNavigation { get; set; } } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_PerformanceReviews.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_PerformanceReviews.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_PerformanceReviews { public long _id { get; set; } public long _owner_id { get; set; } public int _key_Item1 { get; set; } public string _key_Item2 { get; set; } = null!; public string? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_PhoneDirectory.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_PhoneDirectory.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_PhoneDirectory { public long _id { get; set; } public long _owner_id { get; set; } public string _key { get; set; } = null!; public string? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_ProjectMetrics.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_ProjectMetrics.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_ProjectMetrics { public long _id { get; set; } public long _owner_id { get; set; } public string _key { get; set; } = null!; public long? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; public virtual ProjectMetricsProps? _valueNavigation { get; set; } } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_SkillLevels.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_SkillLevels.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_SkillLevels { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_Skills.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_Skills.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_Skills { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_WorkAddress { public long _id { get; set; } public long _owner_id { get; set; } public string? City { get; set; } public string? Street { get; set; } public virtual EmployeeProps_WorkAddress_Building? EmployeeProps_WorkAddress_Building { get; set; } public virtual EmployeeProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_WorkAddress_Building { public long _id { get; set; } public long _owner_id { get; set; } public int? Floor { get; set; } public string? Name { get; set; } public virtual ICollection EmployeeProps_WorkAddress_Building_AccessCodes { get; set; } = new List(); public virtual ICollection EmployeeProps_WorkAddress_Building_Amenities { get; set; } = new List(); public virtual ICollection EmployeeProps_WorkAddress_Building_ElevatorFloors { get; set; } = new List(); public virtual ICollection EmployeeProps_WorkAddress_Building_ParkingSpots { get; set; } = new List(); public virtual EmployeeProps_WorkAddress _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_AccessCodes.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_AccessCodes.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_WorkAddress_Building_AccessCodes { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_WorkAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_Amenities.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_Amenities.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_WorkAddress_Building_Amenities { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_WorkAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_ElevatorFloors.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_ElevatorFloors.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_WorkAddress_Building_ElevatorFloors { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public int? _value { get; set; } public virtual EmployeeProps_WorkAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_ParkingSpots.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/EmployeeProps_WorkAddress_Building_ParkingSpots.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class EmployeeProps_WorkAddress_Building_ParkingSpots { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual EmployeeProps_WorkAddress_Building _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/ExampleResultProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/ExampleResultProps.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class ExampleResultProps { public long _id { get; set; } public string? Tier { get; set; } public virtual ICollection ExampleResultProps_Results { get; set; } = new List(); public virtual objects objects { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/ExampleResultProps_Results.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/ExampleResultProps_Results.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class ExampleResultProps_Results { public long _id { get; set; } public long _owner_id { get; set; } public string _key { get; set; } = null!; public int? Count { get; set; } public int? Time { get; set; } public string? Status { get; set; } public virtual ExampleResultProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/PersonProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/PersonProps.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class PersonProps { public long _id { get; set; } public string? Name { get; set; } public int? Age { get; set; } public string? Email { get; set; } public long? Status { get; set; } public virtual ICollection PersonProps_Roles { get; set; } = new List(); public virtual list_items? StatusNavigation { get; set; } public virtual objects objects { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/PersonProps_Roles.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/PersonProps_Roles.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class PersonProps_Roles { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public long? _value { get; set; } public virtual PersonProps _owner { get; set; } = null!; public virtual list_items? _valueNavigation { get; set; } } Path: redb/redb.Examples/Ef/Entities/ProjectMetricsProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/ProjectMetricsProps.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class ProjectMetricsProps { public long _id { get; set; } public long? ProjectId { get; set; } public long? TasksCompleted { get; set; } public long? TasksTotal { get; set; } public long? BugsFixed { get; set; } public double? Budget { get; set; } public long? TeamSize { get; set; } public virtual ICollection EmployeeProps { get; set; } = new List(); public virtual ICollection EmployeeProps_PastProjects { get; set; } = new List(); public virtual ICollection EmployeeProps_ProjectMetrics { get; set; } = new List(); public virtual ICollection ProjectMetricsProps_Tags { get; set; } = new List(); public virtual ICollection ProjectMetricsProps_Technologies { get; set; } = new List(); public virtual objects objects { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/ProjectMetricsProps_Tags.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/ProjectMetricsProps_Tags.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class ProjectMetricsProps_Tags { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? Name { get; set; } public int? Priority { get; set; } public string? Description { get; set; } public virtual ProjectMetricsProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/ProjectMetricsProps_Technologies.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/ProjectMetricsProps_Technologies.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class ProjectMetricsProps_Technologies { public long _id { get; set; } public long _owner_id { get; set; } public int _idx { get; set; } public string? _value { get; set; } public virtual ProjectMetricsProps _owner { get; set; } = null!; } Path: redb/redb.Examples/Ef/Entities/list_items.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/list_items.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class list_items { public long _id { get; set; } public long _id_list { get; set; } public string? _value { get; set; } public string? _alias { get; set; } public long? _id_object { get; set; } public virtual ICollection PersonProps { get; set; } = new List(); public virtual ICollection PersonProps_Roles { get; set; } = new List(); public virtual lists _id_listNavigation { get; set; } = null!; public virtual objects? _id_objectNavigation { get; set; } } Path: redb/redb.Examples/Ef/Entities/lists.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/lists.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class lists { public long _id { get; set; } public string _name { get; set; } = null!; public string? _alias { get; set; } public virtual ICollection list_items { get; set; } = new List(); } Path: redb/redb.Examples/Ef/Entities/objects.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/Entities/objects.cs ---- using System; using System.Collections.Generic; namespace redb.Examples.Ef.Entities; public partial class objects { public long _id { get; set; } public long? _id_parent { get; set; } public long _id_scheme { get; set; } public long _id_owner { get; set; } public long _id_who_change { get; set; } public DateTime _date_create { get; set; } public DateTime _date_modify { get; set; } public DateTime? _date_begin { get; set; } public DateTime? _date_complete { get; set; } public long? _key { get; set; } public string? _name { get; set; } public string? _note { get; set; } public long? _value_long { get; set; } public string? _value_string { get; set; } public Guid? _value_guid { get; set; } public bool? _value_bool { get; set; } public double? _value_double { get; set; } public decimal? _value_numeric { get; set; } public DateTime? _value_datetime { get; set; } public byte[]? _value_bytes { get; set; } public virtual CityProps? CityProps { get; set; } public virtual DepartmentProps? DepartmentProps { get; set; } public virtual EmployeeProps? EmployeeProps { get; set; } public virtual ExampleResultProps? ExampleResultProps { get; set; } public virtual ICollection Inverse_id_parentNavigation { get; set; } = new List(); public virtual PersonProps? PersonProps { get; set; } public virtual ProjectMetricsProps? ProjectMetricsProps { get; set; } public virtual objects? _id_parentNavigation { get; set; } public virtual ICollection list_items { get; set; } = new List(); } Path: redb/redb.Examples/Ef/FlatContext.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/FlatContext.cs ---- using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef.Entities; namespace redb.Examples.Ef; public partial class FlatContext : DbContext { public FlatContext(DbContextOptions options) : base(options) { } public virtual DbSet CityProps { get; set; } public virtual DbSet CityProps_Coordinates { get; set; } public virtual DbSet DepartmentProps { get; set; } public virtual DbSet EmployeeProps { get; set; } public virtual DbSet EmployeeProps_BonusByYear { get; set; } public virtual DbSet EmployeeProps_CertificationYears { get; set; } public virtual DbSet EmployeeProps_Certifications { get; set; } public virtual DbSet EmployeeProps_Contacts { get; set; } public virtual DbSet EmployeeProps_Contacts_Metadata { get; set; } public virtual DbSet EmployeeProps_Contacts_NotificationHours { get; set; } public virtual DbSet EmployeeProps_DepartmentHistory { get; set; } public virtual DbSet EmployeeProps_DepartmentHistory_BudgetByYear { get; set; } public virtual DbSet EmployeeProps_DepartmentHistory_Leaders { get; set; } public virtual DbSet EmployeeProps_DepartmentHistory_Projects { get; set; } public virtual DbSet EmployeeProps_EmergencyAddress { get; set; } public virtual DbSet EmployeeProps_EmergencyAddress_Building { get; set; } public virtual DbSet EmployeeProps_EmergencyAddress_Building_AccessCodes { get; set; } public virtual DbSet EmployeeProps_EmergencyAddress_Building_Amenities { get; set; } public virtual DbSet EmployeeProps_EmergencyAddress_Building_ElevatorFloors { get; set; } public virtual DbSet EmployeeProps_EmergencyAddress_Building_ParkingSpots { get; set; } public virtual DbSet EmployeeProps_HomeAddress { get; set; } public virtual DbSet EmployeeProps_HomeAddress_Building { get; set; } public virtual DbSet EmployeeProps_HomeAddress_Building_AccessCodes { get; set; } public virtual DbSet EmployeeProps_HomeAddress_Building_Amenities { get; set; } public virtual DbSet EmployeeProps_HomeAddress_Building_ElevatorFloors { get; set; } public virtual DbSet EmployeeProps_HomeAddress_Building_ParkingSpots { get; set; } public virtual DbSet EmployeeProps_OfficeLocations { get; set; } public virtual DbSet EmployeeProps_OfficeLocations_Building { get; set; } public virtual DbSet EmployeeProps_OfficeLocations_Building_AccessCodes { get; set; } public virtual DbSet EmployeeProps_OfficeLocations_Building_Amenities { get; set; } public virtual DbSet EmployeeProps_OfficeLocations_Building_ElevatorFloors { get; set; } public virtual DbSet EmployeeProps_OfficeLocations_Building_ParkingSpots { get; set; } public virtual DbSet EmployeeProps_PastProjects { get; set; } public virtual DbSet EmployeeProps_PerformanceReviews { get; set; } public virtual DbSet EmployeeProps_PhoneDirectory { get; set; } public virtual DbSet EmployeeProps_ProjectMetrics { get; set; } public virtual DbSet EmployeeProps_SkillLevels { get; set; } public virtual DbSet EmployeeProps_Skills { get; set; } public virtual DbSet EmployeeProps_WorkAddress { get; set; } public virtual DbSet EmployeeProps_WorkAddress_Building { get; set; } public virtual DbSet EmployeeProps_WorkAddress_Building_AccessCodes { get; set; } public virtual DbSet EmployeeProps_WorkAddress_Building_Amenities { get; set; } public virtual DbSet EmployeeProps_WorkAddress_Building_ElevatorFloors { get; set; } public virtual DbSet EmployeeProps_WorkAddress_Building_ParkingSpots { get; set; } public virtual DbSet ExampleResultProps { get; set; } public virtual DbSet ExampleResultProps_Results { get; set; } public virtual DbSet PersonProps { get; set; } public virtual DbSet PersonProps_Roles { get; set; } public virtual DbSet ProjectMetricsProps { get; set; } public virtual DbSet ProjectMetricsProps_Tags { get; set; } public virtual DbSet ProjectMetricsProps_Technologies { get; set; } public virtual DbSet list_items { get; set; } public virtual DbSet lists { get; set; } public virtual DbSet objects { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).ValueGeneratedNever(); entity.HasOne(d => d.objects).WithOne(p => p.CityProps) .HasForeignKey(d => d._id) .HasConstraintName("FK_CityProps__id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("CityProps.Coordinates"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_CityProps.Coordinates").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.CityProps_Coordinates) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_CityProps.Coordinates__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).ValueGeneratedNever(); entity.Property(e => e.Budget).HasPrecision(38, 18); entity.HasOne(d => d.objects).WithOne(p => p.DepartmentProps) .HasForeignKey(d => d._id) .HasConstraintName("FK_DepartmentProps__id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).ValueGeneratedNever(); entity.Property(e => e.Salary).HasPrecision(38, 18); entity.HasOne(d => d.CurrentProjectNavigation).WithMany(p => p.EmployeeProps) .HasForeignKey(d => d.CurrentProject) .HasConstraintName("FK_EmployeeProps_CurrentProject"); entity.HasOne(d => d.objects).WithOne(p => p.EmployeeProps) .HasForeignKey(d => d._id) .HasConstraintName("FK_EmployeeProps__id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.BonusByYear"); entity.HasIndex(e => new { e._owner_id, e._key }, "UQ_EmployeeProps.BonusByYear").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.Property(e => e._value).HasPrecision(38, 18); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_BonusByYear) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.BonusByYear__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.CertificationYears"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.CertificationYears").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_CertificationYears) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.CertificationYears__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.Certifications"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.Certifications").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_Certifications) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.Certifications__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.Contacts"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.Contacts").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_Contacts) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.Contacts__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.Contacts.Metadata"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.Contacts.Metadata").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_Contacts_Metadata) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.Contacts.Metadata__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.Contacts.NotificationHours"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.Contacts.NotificationHours").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_Contacts_NotificationHours) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.Contacts.NotificationHours__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.DepartmentHistory"); entity.HasIndex(e => new { e._owner_id, e._key }, "UQ_EmployeeProps.DepartmentHistory").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_DepartmentHistory) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.DepartmentHistory__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.DepartmentHistory.BudgetByYear"); entity.HasIndex(e => new { e._owner_id, e._key }, "UQ_EmployeeProps.DepartmentHistory.BudgetByYear").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_DepartmentHistory_BudgetByYear) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.DepartmentHistory.BudgetByYear__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.DepartmentHistory.Leaders"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.DepartmentHistory.Leaders").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_DepartmentHistory_Leaders) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.DepartmentHistory.Leaders__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.DepartmentHistory.Projects"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.DepartmentHistory.Projects").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_DepartmentHistory_Projects) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.DepartmentHistory.Projects__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.EmergencyAddress"); entity.HasIndex(e => e._owner_id, "UQ_EmployeeProps.EmergencyAddress").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithOne(p => p.EmployeeProps_EmergencyAddress) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.EmergencyAddress__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.EmergencyAddress.Building"); entity.HasIndex(e => e._owner_id, "UQ_EmployeeProps.EmergencyAddress.Building").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithOne(p => p.EmployeeProps_EmergencyAddress_Building) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.EmergencyAddress.Building__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.EmergencyAddress.Building.AccessCodes"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.EmergencyAddress.Building.AccessCodes").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_EmergencyAddress_Building_AccessCodes) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.EmergencyAddress.Building.AccessCodes~20cad047"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.EmergencyAddress.Building.Amenities"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.EmergencyAddress.Building.Amenities").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_EmergencyAddress_Building_Amenities) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.EmergencyAddress.Building.Amenities__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.EmergencyAddress.Building.ElevatorFloors"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.EmergencyAddress.Building.ElevatorFloors").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_EmergencyAddress_Building_ElevatorFloors) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.EmergencyAddress.Building.ElevatorFlo~50707330"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.EmergencyAddress.Building.ParkingSpots"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.EmergencyAddress.Building.ParkingSpots").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_EmergencyAddress_Building_ParkingSpots) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.EmergencyAddress.Building.ParkingSpot~7c1178eb"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.HomeAddress"); entity.HasIndex(e => e._owner_id, "UQ_EmployeeProps.HomeAddress").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithOne(p => p.EmployeeProps_HomeAddress) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.HomeAddress__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.HomeAddress.Building"); entity.HasIndex(e => e._owner_id, "UQ_EmployeeProps.HomeAddress.Building").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithOne(p => p.EmployeeProps_HomeAddress_Building) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.HomeAddress.Building__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.HomeAddress.Building.AccessCodes"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.HomeAddress.Building.AccessCodes").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_HomeAddress_Building_AccessCodes) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.HomeAddress.Building.AccessCodes__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.HomeAddress.Building.Amenities"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.HomeAddress.Building.Amenities").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_HomeAddress_Building_Amenities) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.HomeAddress.Building.Amenities__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.HomeAddress.Building.ElevatorFloors"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.HomeAddress.Building.ElevatorFloors").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_HomeAddress_Building_ElevatorFloors) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.HomeAddress.Building.ElevatorFloors__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.HomeAddress.Building.ParkingSpots"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.HomeAddress.Building.ParkingSpots").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_HomeAddress_Building_ParkingSpots) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.HomeAddress.Building.ParkingSpots__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.OfficeLocations"); entity.HasIndex(e => new { e._owner_id, e._key }, "UQ_EmployeeProps.OfficeLocations").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_OfficeLocations) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.OfficeLocations__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.OfficeLocations.Building"); entity.HasIndex(e => e._owner_id, "UQ_EmployeeProps.OfficeLocations.Building").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithOne(p => p.EmployeeProps_OfficeLocations_Building) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.OfficeLocations.Building__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.OfficeLocations.Building.AccessCodes"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.OfficeLocations.Building.AccessCodes").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_OfficeLocations_Building_AccessCodes) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.OfficeLocations.Building.AccessCodes__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.OfficeLocations.Building.Amenities"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.OfficeLocations.Building.Amenities").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_OfficeLocations_Building_Amenities) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.OfficeLocations.Building.Amenities__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.OfficeLocations.Building.ElevatorFloors"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.OfficeLocations.Building.ElevatorFloors").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_OfficeLocations_Building_ElevatorFloors) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.OfficeLocations.Building.ElevatorFloo~6445e391"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.OfficeLocations.Building.ParkingSpots"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.OfficeLocations.Building.ParkingSpots").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_OfficeLocations_Building_ParkingSpots) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.OfficeLocations.Building.ParkingSpots~439995bd"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.PastProjects"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.PastProjects").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_PastProjects) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.PastProjects__owner_id"); entity.HasOne(d => d._valueNavigation).WithMany(p => p.EmployeeProps_PastProjects) .HasForeignKey(d => d._value) .HasConstraintName("FK_EmployeeProps.PastProjects__value"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.PerformanceReviews"); entity.HasIndex(e => new { e._owner_id, e._key_Item1, e._key_Item2 }, "UQ_EmployeeProps.PerformanceReviews").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_PerformanceReviews) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.PerformanceReviews__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.PhoneDirectory"); entity.HasIndex(e => new { e._owner_id, e._key }, "UQ_EmployeeProps.PhoneDirectory").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_PhoneDirectory) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.PhoneDirectory__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.ProjectMetrics"); entity.HasIndex(e => new { e._owner_id, e._key }, "UQ_EmployeeProps.ProjectMetrics").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_ProjectMetrics) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.ProjectMetrics__owner_id"); entity.HasOne(d => d._valueNavigation).WithMany(p => p.EmployeeProps_ProjectMetrics) .HasForeignKey(d => d._value) .HasConstraintName("FK_EmployeeProps.ProjectMetrics__value"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.SkillLevels"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.SkillLevels").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_SkillLevels) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.SkillLevels__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.Skills"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.Skills").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_Skills) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.Skills__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.WorkAddress"); entity.HasIndex(e => e._owner_id, "UQ_EmployeeProps.WorkAddress").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithOne(p => p.EmployeeProps_WorkAddress) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.WorkAddress__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.WorkAddress.Building"); entity.HasIndex(e => e._owner_id, "UQ_EmployeeProps.WorkAddress.Building").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithOne(p => p.EmployeeProps_WorkAddress_Building) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.WorkAddress.Building__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.WorkAddress.Building.AccessCodes"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.WorkAddress.Building.AccessCodes").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_WorkAddress_Building_AccessCodes) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.WorkAddress.Building.AccessCodes__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.WorkAddress.Building.Amenities"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.WorkAddress.Building.Amenities").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_WorkAddress_Building_Amenities) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.WorkAddress.Building.Amenities__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.WorkAddress.Building.ElevatorFloors"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.WorkAddress.Building.ElevatorFloors").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_WorkAddress_Building_ElevatorFloors) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.WorkAddress.Building.ElevatorFloors__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("EmployeeProps.WorkAddress.Building.ParkingSpots"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_EmployeeProps.WorkAddress.Building.ParkingSpots").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.EmployeeProps_WorkAddress_Building_ParkingSpots) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_EmployeeProps.WorkAddress.Building.ParkingSpots__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).ValueGeneratedNever(); entity.HasOne(d => d.objects).WithOne(p => p.ExampleResultProps) .HasForeignKey(d => d._id) .HasConstraintName("FK_ExampleResultProps__id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("ExampleResultProps.Results"); entity.HasIndex(e => new { e._owner_id, e._key }, "UQ_ExampleResultProps.Results").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.ExampleResultProps_Results) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_ExampleResultProps.Results__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).ValueGeneratedNever(); entity.HasOne(d => d.StatusNavigation).WithMany(p => p.PersonProps) .HasForeignKey(d => d.Status) .HasConstraintName("FK_PersonProps_Status"); entity.HasOne(d => d.objects).WithOne(p => p.PersonProps) .HasForeignKey(d => d._id) .HasConstraintName("FK_PersonProps__id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("PersonProps.Roles"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_PersonProps.Roles").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.PersonProps_Roles) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_PersonProps.Roles__owner_id"); entity.HasOne(d => d._valueNavigation).WithMany(p => p.PersonProps_Roles) .HasForeignKey(d => d._value) .HasConstraintName("FK_PersonProps.Roles__value"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).ValueGeneratedNever(); entity.HasOne(d => d.objects).WithOne(p => p.ProjectMetricsProps) .HasForeignKey(d => d._id) .HasConstraintName("FK_ProjectMetricsProps__id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("ProjectMetricsProps.Tags"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_ProjectMetricsProps.Tags").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.ProjectMetricsProps_Tags) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_ProjectMetricsProps.Tags__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.ToTable("ProjectMetricsProps.Technologies"); entity.HasIndex(e => new { e._owner_id, e._idx }, "UQ_ProjectMetricsProps.Technologies").IsUnique(); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._owner).WithMany(p => p.ProjectMetricsProps_Technologies) .HasForeignKey(d => d._owner_id) .HasConstraintName("FK_ProjectMetricsProps.Technologies__owner_id"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.HasOne(d => d._id_listNavigation).WithMany(p => p.list_items) .HasForeignKey(d => d._id_list) .HasConstraintName("FK_list_items__id_list"); entity.HasOne(d => d._id_objectNavigation).WithMany(p => p.list_items) .HasForeignKey(d => d._id_object) .OnDelete(DeleteBehavior.SetNull) .HasConstraintName("FK_list_items__id_object"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); }); modelBuilder.Entity(entity => { entity.HasKey(e => e._id); entity.Property(e => e._id).HasDefaultValueSql("nextval('flat_identity'::regclass)"); entity.Property(e => e._value_numeric).HasPrecision(38, 18); entity.HasOne(d => d._id_parentNavigation).WithMany(p => p.Inverse_id_parentNavigation) .HasForeignKey(d => d._id_parent) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_objects__id_parent"); }); modelBuilder.HasSequence("flat_identity"); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } Path: redb/redb.Examples/Ef/PersonEfMapping.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/PersonEfMapping.cs ---- using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef.Entities; using Biz = redb.Examples.Models; namespace redb.Examples.Ef; /// /// Persons and list items of the examples through EF Core: PersonProps.Status points at a row of /// list_items, PersonProps.Roles is a table of such pointers. Turned into the business class with /// values, as redb hands them out. /// internal static class PersonEfMapping { /// A new person header with its Props; keys come from the database. public static objects ToEntity(string name, int age, string email, long? statusItemId, IReadOnlyList roleItemIds) { var now = DateTime.UtcNow; return new objects { _id_scheme = EfSchemeIds.Person, _id_owner = 0, _id_who_change = 0, _date_create = now, _date_modify = now, _name = name, PersonProps = new PersonProps { Name = name, Age = age, Email = email, Status = statusItemId, PersonProps_Roles = roleItemIds.Select((id, i) => new PersonProps_Roles { _idx = i, _value = id }).ToList() } }; } /// Every person with its header, status item and role items, as a query. public static IQueryable Persons(this FlatContext db) => db.PersonProps .Include(p => p.objects) .Include(p => p.StatusNavigation) .Include(p => p.PersonProps_Roles).ThenInclude(r => r._valueNavigation) .AsSplitQuery(); /// The list item as redb's business value. public static RedbListItem ToItem(list_items i) => new() { Id = i._id, IdList = i._id_list, Value = i._value ?? string.Empty, Alias = i._alias, IdObject = i._id_object }; /// The business object of a person loaded through . public static RedbObject ToBusiness(PersonProps p) { var h = p.objects; return new RedbObject { id = h._id, parent_id = h._id_parent, scheme_id = h._id_scheme, owner_id = h._id_owner, who_change_id = h._id_who_change, date_create = h._date_create, date_modify = h._date_modify, name = h._name, Props = new Biz.PersonProps { Name = p.Name ?? string.Empty, Age = p.Age ?? 0, Email = p.Email ?? string.Empty, Status = p.StatusNavigation is { } status ? ToItem(status) : null, Roles = p.PersonProps_Roles.Count == 0 ? null : p.PersonProps_Roles.OrderBy(r => r._idx) .Where(r => r._valueNavigation != null) .Select(r => ToItem(r._valueNavigation!)) .ToList() } }; } } Path: redb/redb.Examples/Ef/developer_indexes.sql Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Ef/developer_indexes.sql ---- -- Indexes an EF Core developer adds by hand for the queries of the EF twins (ExamplesEf/*_ef.cs). -- -- The flat schema from `redb flat --ddl-only` already has the keys, the unique constraints and an index on -- every foreign key (EF's own convention). What it lacks are indexes on the columns the queries filter and -- sort by: those an EF application chooses for its own queries, while redb's indexes come out of the box. -- -- E203_ef drops them before the seed and creates them after it, inside the measured time, as E203 sets redb's -- plain indexes aside and rebuilds them. One statement per line; lines starting with -- are skipped. -- Trigram matching for Contains / ILIKE '%...%' (E030, E032). CREATE EXTENSION IF NOT EXISTS pg_trgm; -- Filters and sorting on the employee itself. CREATE INDEX "IX_EmployeeProps_Salary" ON "EmployeeProps" ("Salary"); CREATE INDEX "IX_EmployeeProps_Age" ON "EmployeeProps" ("Age"); CREATE INDEX "IX_EmployeeProps_Department" ON "EmployeeProps" ("Department"); CREATE INDEX "IX_EmployeeProps_Position" ON "EmployeeProps" ("Position"); CREATE INDEX "IX_EmployeeProps_HireDate" ON "EmployeeProps" ("HireDate"); CREATE INDEX "IX_EmployeeProps_LastName" ON "EmployeeProps" ("LastName"); CREATE INDEX "IX_EmployeeProps_LastName_trgm" ON "EmployeeProps" USING gin ("LastName" gin_trgm_ops); -- StartsWith (E031): LIKE 'John%' uses a b-tree only with text_pattern_ops under a non-C collation. CREATE INDEX "IX_EmployeeProps_FirstName_pattern" ON "EmployeeProps" ("FirstName" text_pattern_ops); -- Filters on nested classes. CREATE INDEX "IX_EmployeeProps.HomeAddress_City" ON "EmployeeProps.HomeAddress" ("City"); CREATE INDEX "IX_EmployeeProps.HomeAddress.Building_Floor" ON "EmployeeProps.HomeAddress.Building" ("Floor"); -- Filters on collections: by value first, the owner after it. CREATE INDEX "IX_EmployeeProps.Skills_value_owner" ON "EmployeeProps.Skills" ("_value", "_owner_id"); CREATE INDEX "IX_EmployeeProps.PhoneDirectory_key_owner" ON "EmployeeProps.PhoneDirectory" ("_key", "_owner_id"); CREATE INDEX "IX_EmployeeProps.BonusByYear_key_value" ON "EmployeeProps.BonusByYear" ("_key", "_value"); CREATE INDEX "IX_EmployeeProps.OfficeLocations_key_City" ON "EmployeeProps.OfficeLocations" ("_key", "City"); CREATE INDEX "IX_EmployeeProps.PerformanceReviews_key_value" ON "EmployeeProps.PerformanceReviews" ("_key_Item1", "_key_Item2", "_value"); Path: redb/redb.Examples/Examples/E000_BulkInsert.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E000_BulkInsert.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Example: Bulk insert of complex employee records. /// /// Classic ORM (EF Core) would require ~28 tables: /// /// Employees - main table /// EmployeeSkills - string[] Skills (FK) /// EmployeeSkillLevels - int[] SkillLevels (FK) /// EmployeeCertifications - string[] (FK) /// EmployeeCertificationYears - int[] (FK) /// Addresses - for Home/Work/Emergency (FK) /// BuildingInfos - nested in Address (FK) /// BuildingAmenities - string[] in BuildingInfo (FK) /// BuildingAccessCodes - int[] in BuildingInfo (FK) /// BuildingParkingSpots - string[] (FK) /// BuildingElevatorFloors - int[] (FK) /// Contacts - Contact[] (FK) /// ContactNotificationHours - int[] in Contact (FK) /// ContactMetadata - ContactDetail[] in Contact (FK) /// ProjectMetrics - RedbObject reference /// ProjectTags - Tag[] in ProjectMetrics (FK) /// ProjectTechnologies - string[] in ProjectMetrics (FK) /// EmployeePastProjects - many-to-many (2 FK) /// PhoneDirectory - Dictionary (FK) /// OfficeLocations - Dictionary + Address (2 FK) /// BonusByYear - Dictionary (FK) /// DepartmentHistory - Dictionary (FK) /// Departments - nested class /// DepartmentProjects - string[] (FK) /// DepartmentLeaders - Tag[] (FK) /// DepartmentBudgetByYear - nested Dictionary (FK) /// PerformanceReviews - tuple key Dictionary (FK) /// ProjectMetricsDict - Dictionary with RedbObject (2 FK) /// /// /// INSERTs per employee: ~40-60 records across 28 tables with FK ordering. /// For 100 employees: 4000-6000 INSERTs! /// /// REDB: 2 tables (_objects + _values), ~3000 records, single BulkInsert via COPY. /// [ExampleMeta("E000", "Bulk Insert - Complex Objects", "Setup", ExampleTier.Free, 1, "BulkInsert", "AddNewObjectsAsync", "COPY")] public class E000_BulkInsert : ExampleBase { private static readonly string[] Positions = ["Developer", "Designer", "Manager", "Analyst", "Tester"]; private static readonly string[] Departments = ["Engineering", "Design", "Sales", "Marketing", "Support"]; private static readonly string[] Cities = ["New York", "London", "Berlin", "Tokyo", "Sydney"]; private static readonly string[] Skills = ["C#", "JavaScript", "Python", "SQL", "React", "Azure", "Docker"]; public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); const int count = 100; var employees = CreateEmployees(count); // Bulk insert using COPY protocol (Pro feature) var savedIds = await redb.SaveAsync(employees); sw.Stop(); // Classic ORM: ~25 tables, ~5000 INSERTs with FK ordering // REDB: 2 tables, ~3000 values, single BulkInsert return Ok("E000", "Bulk Insert - Complex Objects", ExampleTier.Free, sw.ElapsedMilliseconds, count, [ $"Inserted: {savedIds.Count} complex objects (vs ~5000 INSERTs in EF)", $"Rate: {savedIds.Count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1)} obj/sec | 2 tables vs ~25" ]); } /// /// Creates employee records with meaningful data for queries. /// /// /// Offset for the generated identities, so repeated batches do not collide. /// Every derived value (position, department, salary, dates) keeps its cyclic /// distribution, only the identity-bearing fields move. Used by E203 to seed volume. /// internal static List> CreateEmployees(int count, int startIndex = 0) { var result = new List>(count); var baseDate = DateTime.Today.AddYears(-5); for (int n = 0; n < count; n++) { int i = startIndex + n; var position = Positions[i % Positions.Length]; var department = Departments[i % Departments.Length]; var city = Cities[i % Cities.Length]; // Age groups: 25-34, 35-44, 45-54, 55-64 var age = 25 + (i % 4) * 10 + (i % 10); // Salary based on position and seniority var baseSalary = position switch { "Manager" => 90000m, "Developer" => 80000m, "Analyst" => 70000m, "Designer" => 65000m, _ => 55000m }; var salary = baseSalary + (i % 20) * 1000; // Hire dates spread over 5 years // Modulo keeps the span inside DateTime range for large startIndex (E203 seeds // ~100k, and i * 30 days would run past year 9999). For i < 365 the result is // unchanged, so E000's own output is identical. var hireDate = baseDate.AddDays((i % 365) * 30); var emp = new RedbObject { name = $"{position} - {department} #{i + 1}", Props = new EmployeeProps { FirstName = $"John{i}", LastName = $"Smith{i}", Age = age, Position = position, Department = department, Salary = salary, HireDate = hireDate, EmployeeCode = $"EMP-{i + 1:D4}", // Skills based on position Skills = GetSkillsForPosition(position, i), SkillLevels = [3 + i % 3, 2 + i % 4, 4 + i % 2], Certifications = i % 3 == 0 ? ["AWS", "Azure"] : i % 2 == 0 ? ["PMP"] : null, CertificationYears = i % 3 == 0 ? [2022, 2023] : i % 2 == 0 ? [2021] : null, // Home address HomeAddress = new Address { City = city, Street = $"{100 + i} Main Street", Building = new BuildingInfo { Floor = 1 + i % 30, Name = $"Tower {(char)('A' + i % 5)}", Amenities = ["Parking", "Gym", "Cafe"], AccessCodes = [1000 + i, 2000 + i] } }, // Work address WorkAddress = new Address { City = city, Street = $"{1 + i % 10} Corporate Plaza", Building = new BuildingInfo { Floor = 5 + i % 20, Name = "HQ Building", Amenities = ["Conference Rooms", "Cafeteria"], AccessCodes = [9000 + i] } }, // Contacts Contacts = [ new Contact { Type = "email", Value = $"john{i}@company.com", IsVerified = i % 2 == 0, NotificationHours = [9, 12, 17], Metadata = [new ContactDetail { Label = "domain", Value = "company.com" }] }, new Contact { Type = "phone", Value = $"+1-555-{1000 + i:D4}", IsVerified = i % 3 == 0, NotificationHours = [10, 15], Metadata = [new ContactDetail { Label = "carrier", Value = "Verizon" }] } ], // Phone directory PhoneDirectory = new Dictionary { ["desk"] = $"x{3000 + i}", ["mobile"] = $"+1-555-{2000 + i:D4}" }, // Bonus history BonusByYear = new Dictionary { [2022] = 5000m + i * 100, [2023] = 6000m + i * 150, [2024] = 7000m + i * 200 }, // Office locations (Dict) OfficeLocations = new Dictionary { ["HQ"] = new Address { City = i % 5 == 0 ? "New York" : city, Street = "1 Corporate Drive", Building = new BuildingInfo { Floor = 1, Name = "Main HQ" } } }, // Performance reviews (Dict<(int,string), string>) PerformanceReviews = new Dictionary<(int Year, string Quarter), string> { [(2024, "Q1")] = i % 3 == 0 ? "Excellent" : i % 2 == 0 ? "Good" : "Satisfactory", [(2024, "Q2")] = i % 4 == 0 ? "Excellent" : "Good" } } }; result.Add(emp); } return result; } private static string[] GetSkillsForPosition(string position, int index) { var skills = position switch { "Developer" => new[] { "C#", "SQL", "Azure", "Docker" }, "Designer" => new[] { "Figma", "Photoshop", "CSS" }, "Analyst" => new[] { "SQL", "Excel", "Python" }, "Manager" => new[] { "Leadership", "Agile", "Communication" }, _ => new[] { "Communication", "Teamwork" } }; var take = position == "Developer" ? 2 + index % 3 : 2 + index % 2; return skills.Take(Math.Min(take, skills.Length)).ToArray(); } } Path: redb/redb.Examples/Examples/E001_SaveAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E001_SaveAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Example: Create and save a new employee. /// [ExampleMeta("E001", "SaveAsync - Create Employee", "CRUD", ExampleTier.Free, 1, "SaveAsync", "Create", "CRUD")] public class E001_SaveAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var employee = new RedbObject { name = "New Developer", Props = new EmployeeProps { FirstName = "Alice", LastName = "Johnson", Age = 28, Position = "Developer", Department = "Engineering", Salary = 85000m, HireDate = DateTime.Today, EmployeeCode = "EMP-NEW-001", Skills = ["C#", "React", "SQL"] } }; var id = await redb.SaveAsync(employee); sw.Stop(); return Ok("E001", "SaveAsync - Create Employee", ExampleTier.Free, sw.ElapsedMilliseconds, [$"Created employee ID: {id}", $"Name: {employee.Props.FirstName} {employee.Props.LastName}"]); } } Path: redb/redb.Examples/Examples/E002_LoadAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E002_LoadAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Example: Load employee by ID. /// [ExampleMeta("E002", "LoadAsync - Load Employee by ID", "CRUD", ExampleTier.Free, 1, "LoadAsync", "Read", "CRUD")] public class E002_LoadAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get any existing employee ID var query = redb.Query().Take(1); var items = await query.ToListAsync(); if (items.Count == 0) { sw.Stop(); return Fail("E002", "LoadAsync - Load Employee by ID", ExampleTier.Free, sw.ElapsedMilliseconds, "No employees found. Run E000 first."); } var id = items[0].Id; var loaded = await redb.LoadAsync(id); if (loaded != null) { EmployeeProps? employee = (EmployeeProps)loaded; } sw.Stop(); return Ok("E002", "LoadAsync - Load Employee by ID", ExampleTier.Free, sw.ElapsedMilliseconds, [$"Loaded ID: {loaded.Id}", $"Employee: {loaded.Props?.FirstName} {loaded.Props?.LastName}, {loaded.Props?.Position}"]); } } Path: redb/redb.Examples/Examples/E003_UniqueKeys.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E003_UniqueKeys.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Unique business keys (V4 [RedbUnique]): the value of a marked field is unique within /// its scheme, enforced by the DATABASE over the hash of the canonical value - not by a /// pre-check that races. The contract shown here: /// /// 1. A duplicate save fails with a typed . /// 2. GetByUniqueAsync finds an object by its key value (server-side, hash lookup). /// 3. NULL never participates: any number of objects may leave the key empty. /// 4. Soft delete releases the key - the trash does not squat on business identifiers. /// /// redb carries TWO unique-key mechanisms, both shown here: /// - [RedbUnique] on a Props field - per-FIELD uniqueness, any scalar type, hash in /// _values._unique; /// - RedbObject.value_unique - a per-OBJECT string key on the object row itself /// (scheme-wide, up to 440 chars, no Props field needed) - the natural slot for an external /// identifier of the whole object. /// [ExampleMeta("E003", "Unique Keys - [RedbUnique] and value_unique", "CRUD", ExampleTier.Free, 3, "Unique", "RedbUnique", "ValueUnique", "GetByUniqueAsync", "SoftDelete", RelatedApis = ["IRedbService.GetByUniqueAsync", "IRedbService.SaveAsync"])] public class E003_UniqueKeys : ExampleBase { public override async Task RunAsync(IRedbService redb) { await redb.SyncSchemeAsync(); // Unique per run so the example is rerunnable on a shared database. var sku = $"SKU-{Guid.NewGuid():N}"[..20]; var sw = Stopwatch.StartNew(); // 1. The first holder of the key wins. var first = new RedbObject { name = "unique-demo-first", Props = new ProductProps { Sku = sku, Title = "First holder", Price = 9.99m } }; var firstId = await redb.SaveAsync(first); // 2. A duplicate is rejected by the database with a typed exception. string rejected; try { await redb.SaveAsync(new RedbObject { name = "unique-demo-duplicate", Props = new ProductProps { Sku = sku, Title = "Impostor", Price = 0.99m } }); rejected = "NOT rejected - this line must never print"; } catch (RedbUniqueViolationException ex) { rejected = $"rejected with {nameof(RedbUniqueViolationException)} (property: {ex.PropertyName ?? "Sku"})"; } // 3. Lookup by key value - one server-side hash probe, no scan. var found = await redb.GetByUniqueAsync(p => p.Sku, sku); // 4. NULL keys do not collide: both keyless products save fine. await redb.SaveAsync(new RedbObject { name = "no-key-a", Props = new ProductProps { Title = "Draft A" } }); await redb.SaveAsync(new RedbObject { name = "no-key-b", Props = new ProductProps { Title = "Draft B" } }); // 5. Soft delete releases the key for the next claimant. await redb.DeleteAsync(firstId); var successor = new RedbObject { name = "unique-demo-successor", Props = new ProductProps { Sku = sku, Title = "Successor", Price = 19.99m } }; var successorId = await redb.SaveAsync(successor); // 6. The OBJECT-level key: value_unique lives on the object row itself - no Props // field involved - and is unique across the whole scheme. var objectKey = $"EXT-{Guid.NewGuid():N}"[..20]; var holder = new RedbObject { name = "object-key-holder", value_unique = objectKey, Props = new ProductProps { Title = "Holder of the object key" } }; await redb.SaveAsync(holder); string objectRejected; try { await redb.SaveAsync(new RedbObject { name = "object-key-impostor", value_unique = objectKey, Props = new ProductProps { Title = "Impostor" } }); objectRejected = "NOT rejected - this line must never print"; } catch (RedbUniqueViolationException ex) { // ex.Kind tells WHICH mechanism fired: ObjectKey here vs Property for [RedbUnique]. objectRejected = $"rejected with {nameof(RedbUniqueViolationException)} (Kind: {ex.Kind})"; } sw.Stop(); return Ok("E003", "Unique Keys - [RedbUnique] and value_unique", ExampleTier.Free, sw.ElapsedMilliseconds, 5, [ $"Field key [RedbUnique]: {sku}", $"Duplicate: {rejected}", $"GetByUniqueAsync found: #{found?.Id} ({found?.Props.Title})", "Two keyless (NULL) products saved side by side", $"Soft delete released the key: successor #{successorId} took it", $"Object key (value_unique): {objectKey}, duplicate {objectRejected}" ]); } } Path: redb/redb.Examples/Examples/E004_SubtreeAndElementKeys.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E004_SubtreeAndElementKeys.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Exceptions; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Unique keys beyond a root scalar (V4). Props are stored flat, one row per value, and the /// storage already maintains a canonical hash for every nested class and collection - so /// [RedbUnique] reaches four more shapes with the same database-enforced index: /// /// 1. A scalar INSIDE a nested class - a lambda path (d => d.Identity!.Serial) is the key. /// 2. A whole SUBTREE - the content of a nested class, in canonical form, is the key. /// 3. A whole COLLECTION - the ordered list is the key; the same numbers in another order differ. /// 4. ELEMENTS of a collection with a scope: UniqueScope.Collection forbids duplicates /// inside one object's collection, UniqueScope.Scheme makes every element value unique /// across all objects of the scheme (and probeable by GetByUniqueAsync). /// /// Plus [RedbTags]: a free-form marker written to the scheme and structure metadata for /// applications and extensions to read back. /// [ExampleMeta("E004", "Unique Keys - nested, subtree and element keys, [RedbTags]", "CRUD", ExampleTier.Free, 4, "Unique", "RedbUnique", "UniqueScope", "RedbTags", "GetByUniqueAsync", RelatedApis = ["IRedbService.GetByUniqueAsync", "IRedbService.SaveAsync", "IRedbService.GetSchemeByTypeAsync"])] public class E004_SubtreeAndElementKeys : ExampleBase { public override async Task RunAsync(IRedbService redb) { await redb.SyncSchemeAsync(); // Unique per run so the example is rerunnable on a shared database. var run = Guid.NewGuid().ToString("N")[..8]; var sw = Stopwatch.StartNew(); // 1. Key on a scalar inside a nested class: same rules as a root key. var serial = $"SN-{run}"; var alphaId = await redb.SaveAsync(Device("alpha", d => d.Identity = new DeviceIdentity { Serial = serial, Vendor = "Acme" })); var nestedDup = await Rejected(() => redb.SaveAsync(Device("alpha-dup", d => d.Identity = new DeviceIdentity { Serial = serial, Vendor = "Other" }))); var bySerial = await redb.GetByUniqueAsync(d => d.Identity!.Serial, serial); // 2. Subtree key: the CONTENT of the nested class is the key. Same content - rejected; // one field different - a different key. The lookup canonicalises the probe object // the same way the save did. var region = $"eu-{run}"; var betaId = await redb.SaveAsync(Device("beta", d => d.Config = new DeviceConfig { Region = region, Tier = 2 })); var subtreeDup = await Rejected(() => redb.SaveAsync(Device("beta-dup", d => d.Config = new DeviceConfig { Region = region, Tier = 2 }))); await redb.SaveAsync(Device("beta-tier3", d => d.Config = new DeviceConfig { Region = region, Tier = 3 })); var byConfig = await redb.GetByUniqueAsync(d => d.Config, new DeviceConfig { Region = region, Tier = 2 }); // 3. Subtree key on a collection: the ordered list is the key. var basePort = Random.Shared.Next(10_000, 60_000); List ports = [basePort, basePort + 1, basePort + 2]; await redb.SaveAsync(Device("gamma", d => d.Ports = ports)); var listDup = await Rejected(() => redb.SaveAsync(Device("gamma-dup", d => d.Ports = [.. ports]))); await redb.SaveAsync(Device("gamma-reversed", d => d.Ports = [basePort + 2, basePort + 1, basePort])); // 4. Element keys, Collection scope: no duplicate label inside ONE device. Another device // may carry the same label - the scope is the collection, not the scheme. await redb.SaveAsync(Device("delta", d => d.Labels = ["rack-1", "spare"])); await redb.SaveAsync(Device("delta-twin", d => d.Labels = ["rack-1"])); var elementDup = await Rejected(() => redb.SaveAsync(Device("delta-dup", d => d.Labels = ["rack-1", "rack-1"]))); // 5. Element keys, Scheme scope: a MAC address belongs to one device in the whole scheme, // and the holder is found by the element value. var mac = $"02:{run[..2]}:{run[2..4]}:{run[4..6]}:00:01"; // The second address comes from the same run characters as the first: the key is unique across the // scheme, and two characters alone (256 values) collide with earlier runs of this example. var epsilonId = await redb.SaveAsync(Device("epsilon", d => d.MacAddresses = [mac, $"02:{run[..2]}:{run[2..4]}:{run[4..6]}:00:02"])); var macDup = await Rejected(() => redb.SaveAsync(Device("epsilon-dup", d => d.MacAddresses = [mac]))); var byMac = await redb.GetByUniqueAsync(d => d.MacAddresses, mac); // 6. [RedbTags]: the markers are metadata - read them back from the synced scheme. var scheme = await redb.GetSchemeByTypeAsync(); var schemeTags = scheme?.Tags; var macTags = scheme?.GetStructureByName(nameof(DeviceProps.MacAddresses))?.Tags; sw.Stop(); // The example is a contract probe: a duplicate that slipped through, a lookup that missed // or a tag that did not land is a FAIL, not a line in the report. var problems = new List(); if (!nestedDup.StartsWith("rejected")) problems.Add("nested key: duplicate was not rejected"); if (bySerial?.Id != alphaId) problems.Add("nested key: lookup by lambda path missed"); if (!subtreeDup.StartsWith("rejected")) problems.Add("subtree key: duplicate content was not rejected"); if (byConfig?.Id != betaId) problems.Add("subtree key: lookup by content missed"); if (!listDup.StartsWith("rejected")) problems.Add("collection key: duplicate list was not rejected"); if (!elementDup.StartsWith("rejected")) problems.Add("element key (Collection): duplicate inside one device was not rejected"); if (!macDup.StartsWith("rejected")) problems.Add("element key (Scheme): duplicate across devices was not rejected"); if (byMac?.Id != epsilonId) problems.Add("element key (Scheme): lookup by element value missed"); if (schemeTags != "examples,e004") problems.Add($"[RedbTags] on the scheme did not land: '{schemeTags}'"); if (macTags != "network") problems.Add($"[RedbTags] on the structure did not land: '{macTags}'"); if (problems.Count > 0) return Fail("E004", "Unique Keys - nested, subtree and element keys, [RedbTags]", ExampleTier.Free, sw.ElapsedMilliseconds, string.Join("; ", problems)); return Ok("E004", "Unique Keys - nested, subtree and element keys, [RedbTags]", ExampleTier.Free, sw.ElapsedMilliseconds, 9, [ $"Nested key Identity.Serial = {serial}: holder #{alphaId}, duplicate {nestedDup}, lookup by lambda path found #{bySerial?.Id}", $"Subtree key Config {{{region}, tier 2}}: holder #{betaId}, duplicate {subtreeDup}, tier 3 saved as a different key, lookup by content found #{byConfig?.Id}", $"Collection key Ports [{string.Join(",", ports)}]: duplicate {listDup}, reversed order saved as a different key", $"Element keys, Collection scope: 'rack-1' in two devices is fine, twice in one device {elementDup}", $"Element keys, Scheme scope: MAC {mac} held by #{epsilonId}, duplicate {macDup}, lookup by element found #{byMac?.Id}", $"[RedbTags]: scheme '{schemeTags}', structure MacAddresses '{macTags}'" ]); } private static RedbObject Device(string title, Action configure) { var props = new DeviceProps { Title = title }; configure(props); return new RedbObject { name = $"e004-{title}", Props = props }; } /// Runs a save that must fail on a key and reports which key fired. private static async Task Rejected(Func> save) { try { await save(); return "NOT rejected - this line must never print"; } catch (RedbUniqueViolationException ex) { return $"rejected ({ex.Kind}, {ex.PropertyName})"; } } } Path: redb/redb.Examples/Examples/E010_WhereSimple.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E010_WhereSimple.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Example: Simple Where filter by salary. /// [ExampleMeta("E010", "Where - Filter by Salary", "Query", ExampleTier.Free, 1, "Where", "Query", "Filter", RelatedApis = ["IRedbQueryable.Where", "IRedbService.Query"])] public class E010_WhereSimple : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.Salary > 75000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E010", "Where - Filter by Salary", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Salary > 75000"]); } } Path: redb/redb.Examples/Examples/E011_WhereAnd.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E011_WhereAnd.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Example: Where with AND - filter by age and salary. /// [ExampleMeta("E011", "Where - AND Condition", "Query", ExampleTier.Free, 2, "Where", "Query", "AND")] public class E011_WhereAnd : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.Age >= 30 && e.Salary > 70000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E011", "Where - AND Condition", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Age >= 30 AND Salary > 70000"]); } } Path: redb/redb.Examples/Examples/E012_WhereOr.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E012_WhereOr.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees using OR condition. /// Find juniors (under 30) OR high earners (salary over 90k). /// [ExampleMeta("E012", "Where - OR Condition", "Query", ExampleTier.Free, 1, "Where", "Query", "OR")] public class E012_WhereOr : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.Age < 30 || e.Salary > 90000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E012", "Where - OR Condition", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Age < 30 OR Salary > 90000"]); } } Path: redb/redb.Examples/Examples/E013_WhereNot.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E013_WhereNot.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees using NOT equal condition. /// Find all non-managers. /// [ExampleMeta("E013", "Where - NOT Equal", "Query", ExampleTier.Free, 1, "Where", "Query", "NOT")] public class E013_WhereNot : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.Position != "Manager") .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E013", "Where - NOT Equal", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Position != 'Manager'"]); } } Path: redb/redb.Examples/Examples/E014_WhereRange.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E014_WhereRange.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees by salary range. /// Find mid-level earners between 60k and 90k. /// [ExampleMeta("E014", "Where - Range Condition", "Query", ExampleTier.Free, 1, "Where", "Query", "Range")] public class E014_WhereRange : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.Salary >= 60000m && e.Salary < 90000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E014", "Where - Range Condition", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: 60k <= Salary < 90k"]); } } Path: redb/redb.Examples/Examples/E015_WhereTripleAnd.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E015_WhereTripleAnd.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees using triple AND condition. /// Find experienced developers with high salary, highest paid first. /// [ExampleMeta("E015", "Where - Triple AND", "Query", ExampleTier.Free, 2, "Where", "AND", "Complex")] public class E015_WhereTripleAnd : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.Position != "" && e.Age >= 30 && e.Salary > 70000m) .OrderByDescending(e => e.Salary) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E015", "Where - Triple AND", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Position != '' AND Age >= 30 AND Salary > 70k, ORDER BY Salary DESC, top 100"]); } } Path: redb/redb.Examples/Examples/E016_WhereChain.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E016_WhereChain.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees using chained Where() calls. /// Each Where() adds another condition. /// [ExampleMeta("E016", "Where - Chained Filters", "Query", ExampleTier.Free, 2, "Where", "Chain")] public class E016_WhereChain : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Chained Where() calls - equivalent to AND var query = redb.Query() .Where(e => e.Age >= 30) .Where(e => e.Salary > 60000m) .Where(e => e.Department != "Support") .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E016", "Where - Chained Filters", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: .Where(Age).Where(Salary).Where(Dept)"]); } } Path: redb/redb.Examples/Examples/E020_DateTimeGreater.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E020_DateTimeGreater.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees by hire date. /// Find employees hired after a specific date. /// [ExampleMeta("E020", "Where - DateTime Greater", "Query", ExampleTier.Free, 1, "Where", "DateTime", "HireDate")] public class E020_DateTimeGreater : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees hired in last 2 years var cutoffDate = DateTime.Today.AddYears(-2); var query = redb.Query() .Where(e => e.HireDate >= cutoffDate) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E020", "Where - DateTime Greater", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: HireDate >= {cutoffDate:yyyy-MM-dd}"]); } } Path: redb/redb.Examples/Examples/E021_DateTimeRange.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E021_DateTimeRange.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees by date range. /// Find employees hired within specific period. /// [ExampleMeta("E021", "Where - DateTime Range", "Query", ExampleTier.Free, 1, "Where", "DateTime", "Range")] public class E021_DateTimeRange : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var startDate = DateTime.Today.AddYears(-3); var endDate = DateTime.Today.AddYears(-1); var query = redb.Query() .Where(e => e.HireDate >= startDate && e.HireDate < endDate) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E021", "Where - DateTime Range", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: HireDate in [{startDate:yyyy-MM-dd}, {endDate:yyyy-MM-dd})"]); } } Path: redb/redb.Examples/Examples/E030_StringContains.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E030_StringContains.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees using String.Contains. /// Find employees whose last name contains "Smith". /// [ExampleMeta("E030", "Where - String Contains", "Query", ExampleTier.Free, 1, "Where", "String", "Contains")] public class E030_StringContains : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.LastName.Contains("Smith")) .Take(100); // Uncomment to see generated SQL: //var sql = await query.ToSqlStringAsync(); //Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E030", "Where - String Contains", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: LastName.Contains('Smith')"]); } } Path: redb/redb.Examples/Examples/E031_StringStartsWith.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E031_StringStartsWith.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees using String.StartsWith. /// Find employees whose first name starts with "John". /// [ExampleMeta("E031", "Where - String StartsWith", "Query", ExampleTier.Free, 1, "Where", "String", "StartsWith")] public class E031_StringStartsWith : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.FirstName.StartsWith("John")) .Take(100); // Uncomment to see generated SQL: //var sql = await query.ToSqlStringAsync(); //Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E031", "Where - String StartsWith", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: FirstName.StartsWith('John')"]); } } Path: redb/redb.Examples/Examples/E032_StringContainsIgnoreCase.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E032_StringContainsIgnoreCase.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter using case-insensitive String.Contains. /// Uses StringComparison.OrdinalIgnoreCase for accent/case agnostic search. /// [ExampleMeta("E032", "Where - Contains IgnoreCase", "Query", ExampleTier.Free, 32, "Where", "String", "Contains", "IgnoreCase", RelatedApis = ["IRedbQueryable.Where"])] public class E032_StringContainsIgnoreCase : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Case-insensitive search: "smith" matches "Smith", "SMITH", etc. var query = redb.Query() .Where(e => e.LastName.Contains("smith", StringComparison.OrdinalIgnoreCase)) .Take(100); // Uncomment to see generated SQL: //var sql = await query.ToSqlStringAsync(); //Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); var sample = result.FirstOrDefault()?.Props?.LastName ?? "N/A"; return Ok("E032", "Where - Contains IgnoreCase", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: 'smith' (case-insensitive)", $"Found: {sample}"]); } } Path: redb/redb.Examples/Examples/E040_NestedProperty.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E040_NestedProperty.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees by nested property. /// Find employees who live in London. /// [ExampleMeta("E040", "Where - Nested Property", "Query", ExampleTier.Free, 2, "Where", "Nested", "Address")] public class E040_NestedProperty : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.HomeAddress!.City == "London") .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E040", "Where - Nested Property", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: HomeAddress.City == 'London'"]); } } Path: redb/redb.Examples/Examples/E041_DeepNested.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E041_DeepNested.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees by deeply nested property. /// Find employees on high floors in their home building. /// [ExampleMeta("E041", "Where - Deep Nested Property", "Query", ExampleTier.Pro, 2, "Where", "Nested", "Building")] public class E041_DeepNested : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.HomeAddress!.Building!.Floor > 10) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E041", "Where - Deep Nested Property", ExampleTier.Pro, sw.ElapsedMilliseconds, result.Count, [$"Filter: HomeAddress.Building.Floor > 10"]); } } Path: redb/redb.Examples/Examples/E050_ArrayContains.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E050_ArrayContains.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees by skill using Array.Contains. /// Find all C# developers. /// [ExampleMeta("E050", "Array Contains - Find by Skill", "Query", ExampleTier.Free, 2, "Array", "Contains", "Skills", "Pro")] public class E050_ArrayContains : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Query array property with Contains var query = redb.Query() .Where(e => e.Skills!.Contains("C#")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E050", "Array Contains - Find by Skill", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Skills.Contains('C#')"]); } } Path: redb/redb.Examples/Examples/E051_ArrayMultiple.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E051_ArrayMultiple.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees with multiple skills using Array.Contains with OR. /// Find developers who know C# OR Python. /// [ExampleMeta("E051", "Array Contains - Multiple OR", "Query", ExampleTier.Free, 2, "Array", "Contains", "OR", "Pro")] public class E051_ArrayMultiple : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Multiple array Contains with OR var query = redb.Query() .Where(e => e.Skills!.Contains("C#") || e.Skills!.Contains("Python")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E051", "Array Contains - Multiple OR", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Skills has 'C#' OR 'Python'"]); } } Path: redb/redb.Examples/Examples/E052_ArrayNotContains.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E052_ArrayNotContains.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees excluding specific skill. /// Find developers who don't have "intern" skill. /// [ExampleMeta("E052", "Array NOT Contains", "Query", ExampleTier.Free, 2, "Array", "Contains", "NOT", "Pro")] public class E052_ArrayNotContains : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: NOT Contains - exclude employees with specific skill var query = redb.Query() .Where(e => e.Skills!.Contains("C#") && !e.Skills!.Contains("intern")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E052", "Array NOT Contains", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Skills has 'C#' AND NOT 'intern'"]); } } Path: redb/redb.Examples/Examples/E053_ArrayWithConditions.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E053_ArrayWithConditions.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees combining array Contains with other conditions (Pro). /// Find senior C# developers over 30. /// [ExampleMeta("E053", "Array Contains + Conditions", "Query", ExampleTier.Free, 2, "Array", "Contains", "AND", "Pro")] public class E053_ArrayWithConditions : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Combine array Contains with other conditions var query = redb.Query() .Where(e => e.Skills!.Contains("C#") && e.Age >= 30 && e.Salary > 70000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E053", "Array Contains + Conditions", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: Skills has 'C#' AND Age >= 30 AND Salary > 70k"]); } } Path: redb/redb.Examples/Examples/E060_DictContainsKey.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E060_DictContainsKey.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees using Dictionary.ContainsKey. /// Find employees who have a desk phone. /// [ExampleMeta("E060", "Dict ContainsKey - Phone Directory", "Query", ExampleTier.Free, 2, "Dictionary", "ContainsKey", "Pro")] public class E060_DictContainsKey : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Query dictionary with ContainsKey var query = redb.Query() .Where(e => e.PhoneDirectory!.ContainsKey("desk")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E060", "Dict ContainsKey - Phone Directory", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: PhoneDirectory.ContainsKey('desk')"]); } } Path: redb/redb.Examples/Examples/E061_DictIndexer.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E061_DictIndexer.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees using Dictionary indexer. /// Find employees with bonus over 6000 in 2023. /// [ExampleMeta("E061", "Dict Indexer - Bonus by Year", "Query", ExampleTier.Free, 2, "Dictionary", "Indexer", "Pro")] public class E061_DictIndexer : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Query dictionary with indexer var query = redb.Query() .Where(e => e.BonusByYear![2023] > 6000m) .Take(100); // Uncomment to see generated SQL: //var sql = await query.ToSqlStringAsync(); //Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E061", "Dict Indexer - Bonus by Year", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: BonusByYear[2023] > 6000"]); } } Path: redb/redb.Examples/Examples/E062_DictNestedClass.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E062_DictNestedClass.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees using Dict indexer with nested class (Pro). /// Find employees whose HQ office is in specific city. /// [ExampleMeta("E062", "Dict - Nested Class Property", "Query", ExampleTier.Free, 3, "Dictionary", "Nested", "Class", "Pro")] public class E062_DictNestedClass : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Dictionary with nested property access var query = redb.Query() .Where(e => e.OfficeLocations!["HQ"].City == "New York") .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E062", "Dict - Nested Class Property", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: OfficeLocations['HQ'].City == 'New York'"]); } } Path: redb/redb.Examples/Examples/E063_DictTupleKey.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E063_DictTupleKey.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees using Dict with tuple key (Pro). /// Find employees with specific performance review. /// [ExampleMeta("E063", "Dict - Tuple Key", "Query", ExampleTier.Free, 3, "Dictionary", "Tuple", "Key", "Pro")] public class E063_DictTupleKey : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Dictionary<(int Year, string Quarter), string> with tuple key // Tuple key must be in a variable for Expression Tree to work var reviewKey = (Year: 2024, Quarter: "Q1"); var query = redb.Query() .Where(e => e.PerformanceReviews![reviewKey] == "Excellent") .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E063", "Dict - Tuple Key", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Filter: PerformanceReviews[(2024, 'Q1')] == 'Excellent'"]); } } Path: redb/redb.Examples/Examples/E070_CountAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E070_CountAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Count employees using CountAsync. /// Get total count and filtered count. /// [ExampleMeta("E070", "CountAsync - Total and Filtered", "Query", ExampleTier.Free, 1, "Count", "Aggregate")] public class E070_CountAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Total count var totalCount = await redb.Query().CountAsync(); // Filtered count var managersCount = await redb.Query() .Where(e => e.Position == "Manager") .CountAsync(); // Filtered by a field two nested classes deep var highFloorCount = await redb.Query() .Where(e => e.HomeAddress!.Building!.Floor > 20) .CountAsync(); sw.Stop(); return Ok("E070", "CountAsync - Total and Filtered", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Total: {totalCount}, Managers: {managersCount}, Home floor above 20: {highFloorCount}"]); } } Path: redb/redb.Examples/Examples/E071_AnyAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E071_AnyAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Check if any employees exist using AnyAsync(). /// Returns true if at least one record exists. /// [ExampleMeta("E071", "AnyAsync - Check Existence", "Query", ExampleTier.Free, 71, "Any", "Exists", RelatedApis = ["IRedbQueryable.AnyAsync"])] public class E071_AnyAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Check if any employees exist (no predicate) var query = redb.Query(); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var anyExist = await query.AnyAsync(); // Existence within a set filtered by a field two nested classes deep var anyOnTopFloor = await redb.Query() .Where(e => e.HomeAddress!.Building!.Floor == 30) .AnyAsync(); sw.Stop(); return Ok("E071", "AnyAsync - Check Existence", ExampleTier.Free, sw.ElapsedMilliseconds, anyExist ? 1 : 0, [$"Any employees exist: {anyExist}", $"Any living on floor 30: {anyOnTopFloor}"]); } } Path: redb/redb.Examples/Examples/E072_AnyWithPredicate.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E072_AnyWithPredicate.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Check if any employees match a condition using AnyAsync(predicate). /// More efficient than Where().AnyAsync() - stops at first match. /// [ExampleMeta("E072", "AnyAsync - With Predicate", "Query", ExampleTier.Free, 72, "Any", "Predicate", "Filter", RelatedApis = ["IRedbQueryable.AnyAsync"])] public class E072_AnyWithPredicate : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Check if any high earners exist (salary > 100k) var query = redb.Query(); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var anyHighEarners = await query.AnyAsync(e => e.Salary > 100_000m); // Predicate over a field one nested class deep and a field two nested classes deep var anyBerlinHighFloor = await query.AnyAsync(e => e.HomeAddress!.City == "Berlin" && e.HomeAddress!.Building!.Floor > 25); sw.Stop(); return Ok("E072", "AnyAsync - With Predicate", ExampleTier.Free, sw.ElapsedMilliseconds, anyHighEarners ? 1 : 0, [$"Any with Salary > 100k: {anyHighEarners}", $"Any in Berlin above floor 25: {anyBerlinHighFloor}"]); } } Path: redb/redb.Examples/Examples/E073_AllAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E073_AllAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Check if ALL employees match a condition using AllAsync(predicate). /// Returns true only if every record satisfies the predicate. /// [ExampleMeta("E073", "AllAsync - Check All Match", "Query", ExampleTier.Free, 73, "All", "Predicate", "Validation", RelatedApis = ["IRedbQueryable.AllAsync"])] public class E073_AllAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Check if all employees have non-negative salary var allNonNegativeSalary = await redb.Query() .AllAsync(e => e.Salary >= 0); // Check if all high earners (>100k) are over 25 years old var allHighEarnersOver25 = await redb.Query() .Where(e => e.Salary > 100000m) .AllAsync(e => e.Age > 25); // Negative check: are ALL employees millionaires? (expect false) var allMillionaires = await redb.Query() .AllAsync(e => e.Salary > 1_000_000m); // Filter and check both on nested classes: everyone in Berlin lives on floor 1 or higher var allBerlinFloorsValid = await redb.Query() .Where(e => e.HomeAddress!.City == "Berlin") .AllAsync(e => e.HomeAddress!.Building!.Floor >= 1); sw.Stop(); // Count passed validations var checks = new[] { allNonNegativeSalary, allHighEarnersOver25, allBerlinFloorsValid }; var passedCount = checks.Count(c => c); return Ok("E073", "AllAsync - Check All Match", ExampleTier.Free, sw.ElapsedMilliseconds, passedCount, [$"All Salary >= 0: {allNonNegativeSalary}", $"All high earners (>100k) over 25: {allHighEarnersOver25}", $"All millionaires (>1M): {allMillionaires} (expected false)", $"All in Berlin on floor 1 or higher: {allBerlinFloorsValid}"]); } } Path: redb/redb.Examples/Examples/E074_WhereIn.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E074_WhereIn.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees by a list of values using WhereIn. /// Equivalent to SQL IN clause - much faster than multiple OR conditions. /// [ExampleMeta("E074", "WhereIn - Filter by List", "Query", ExampleTier.Free, 74, "WhereIn", "IN", "Filter", "List", RelatedApis = ["IRedbQueryable.WhereIn"])] public class E074_WhereIn : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Filter by list of departments var targetDepartments = new[] { "Engineering", "Sales", "Marketing" }; var query = redb.Query() .WhereIn(e => e.Department, targetDepartments) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); // Execute query var results = await query.ToListAsync(); // Count total matches (without loading all) var totalCount = await redb.Query() .WhereIn(e => e.Department, targetDepartments) .CountAsync(); sw.Stop(); return Ok("E074", "WhereIn - Filter by List", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Loaded: {results.Count}, Total: {totalCount}", $"Depts: {string.Join(", ", targetDepartments)}"]); } } Path: redb/redb.Examples/Examples/E075_Select.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E075_Select.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Project specific fields using Select (server-side projection). /// Fetches only requested Props fields, reducing data transfer, from every depth: the employee itself, /// nested classes one and two levels deep, and dictionary entries holding a scalar, a class and a class /// inside that class. /// [ExampleMeta("E075", "Select - Projection", "Query", ExampleTier.Free, 75, "Select", "Projection", "Fields", RelatedApis = ["IRedbQueryable.Select"])] public class E075_Select : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Server-side projection - fetches only selected Props fields var query = redb.Query() .Where(x => x.Salary > 60000m && x.HomeAddress!.Building!.Floor > 10) .OrderByDescending(x => x.Salary) .ThenBy(x => x.LastName) .Take(100) .Select(x => new { // Level 0: fields of the employee x.Props.FirstName, x.Props.LastName, x.Props.Salary, // Level 1: a nested class HomeCity = x.Props.HomeAddress!.City, WorkCity = x.Props.WorkAddress!.City, // Level 2: a class inside a nested class HomeFloor = x.Props.HomeAddress!.Building!.Floor, WorkBuilding = x.Props.WorkAddress!.Building!.Name, // Dictionary entries: a scalar, a class, a class inside it DeskPhone = x.Props.PhoneDirectory!["desk"], HqCity = x.Props.OfficeLocations!["HQ"].City, HqFloor = x.Props.OfficeLocations!["HQ"].Building!.Floor }); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); var first = results.FirstOrDefault(); var fullName = first != null ? $"{first.FirstName} {first.LastName}" : "N/A"; return Ok("E075", "Select - Projection", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Salary > 60000 AND HomeAddress.Building.Floor > 10, ORDER BY Salary DESC, LastName", $"Projected: {results.Count}", $"First: {fullName}, Salary: {first?.Salary:N0}", $"Home: {first?.HomeCity}, floor {first?.HomeFloor}; Work: {first?.WorkCity}, {first?.WorkBuilding}", $"Desk phone: {first?.DeskPhone}; HQ: {first?.HqCity}, floor {first?.HqFloor}"]); } } Path: redb/redb.Examples/Examples/E076_Distinct.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E076_Distinct.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Get unique objects by Props hash using Distinct(). /// Server-side: SELECT DISTINCT ON (_hash) - deduplicates by Props content. /// [ExampleMeta("E076", "Distinct - Unique by Props", "Query", ExampleTier.Free, 76, "Distinct", "Unique", "Dedupe", RelatedApis = ["IRedbQueryable.Distinct"])] public class E076_Distinct : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Server-side Distinct by Props hash var query = redb.Query() .Distinct() .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var uniqueEmployees = await query.ToListAsync(); // Compare with total count var totalCount = await redb.Query().CountAsync(); sw.Stop(); return Ok("E076", "Distinct - Unique by Props", ExampleTier.Free, sw.ElapsedMilliseconds, uniqueEmployees.Count, [$"Unique loaded: {uniqueEmployees.Count}", $"Total in DB: {totalCount}"]); } } Path: redb/redb.Examples/Examples/E080_OrderBy.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E080_OrderBy.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Sort employees by salary using OrderBy. /// Get top 5 lowest and highest earners. /// [ExampleMeta("E080", "OrderBy - Sort by Salary", "Query", ExampleTier.Free, 1, "OrderBy", "Sort")] public class E080_OrderBy : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ascending - lowest earners var lowest = await redb.Query() .OrderBy(e => e.Salary) .Take(5) .ToListAsync(); // Descending - highest earners var highest = await redb.Query() .OrderByDescending(e => e.Salary) .Take(5) .ToListAsync(); sw.Stop(); var lowestSalary = lowest.FirstOrDefault()?.Props?.Salary ?? 0; var highestSalary = highest.FirstOrDefault()?.Props?.Salary ?? 0; return Ok("E080", "OrderBy - Sort by Salary", ExampleTier.Free, sw.ElapsedMilliseconds, lowest.Count + highest.Count, [$"Lowest: ${lowestSalary:N0}, Highest: ${highestSalary:N0}"]); } } Path: redb/redb.Examples/Examples/E081_OrderByThenBy.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E081_OrderByThenBy.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Sort employees by multiple fields using ThenBy. /// Sort by department, then by salary descending. /// [ExampleMeta("E081", "OrderBy + ThenBy", "Query", ExampleTier.Free, 1, "OrderBy", "ThenBy", "Sort")] public class E081_OrderByThenBy : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .OrderBy(e => e.Department) .ThenByDescending(e => e.Salary) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); var first = result.FirstOrDefault(); var info = first?.Props != null ? $"{first.Props.Department}: ${first.Props.Salary:N0}" : "-"; return Ok("E081", "OrderBy + ThenBy", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Sort: Department ASC, Salary DESC", $"First: {info}"]); } } Path: redb/redb.Examples/Examples/E082_SkipTake.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E082_SkipTake.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Paginate employees using Skip and Take. /// Get page 2 with 10 items per page. /// [ExampleMeta("E082", "Skip/Take - Pagination", "Query", ExampleTier.Free, 1, "Skip", "Take", "Pagination")] public class E082_SkipTake : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); const int pageSize = 10; const int page = 2; // 0-based would skip 10 var query = redb.Query() .OrderBy(e => e.LastName) .Skip((page - 1) * pageSize) .Take(pageSize); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E082", "Skip/Take - Pagination", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, [$"Page {page}, size {pageSize}", $"Skip {(page - 1) * pageSize}, Take {pageSize}"]); } } Path: redb/redb.Examples/Examples/E083_OrderByDescending.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E083_OrderByDescending.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Sort employees in descending order using OrderByDescending. /// Get top earners and most experienced employees. /// [ExampleMeta("E083", "OrderByDescending - Reverse Sort", "Query", ExampleTier.Free, 83, "OrderByDescending", "Sort", "Descending", RelatedApis = ["IRedbQueryable.OrderByDescending"])] public class E083_OrderByDescending : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Top earners (highest salary first) var query = redb.Query() .OrderByDescending(e => e.Salary) .Take(5); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var topEarners = await query.ToListAsync(); // Oldest employees (highest age first) var oldest = await redb.Query() .OrderByDescending(e => e.Age) .Take(5) .ToListAsync(); sw.Stop(); var topSalary = topEarners.FirstOrDefault()?.Props?.Salary ?? 0; var oldestAge = oldest.FirstOrDefault()?.Props?.Age ?? 0; return Ok("E083", "OrderByDescending - Reverse Sort", ExampleTier.Free, sw.ElapsedMilliseconds, topEarners.Count + oldest.Count, [$"Top salary: ${topSalary:N0}", $"Oldest age: {oldestAge}"]); } } Path: redb/redb.Examples/Examples/E087_TreeCleanup.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E087_TreeCleanup.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Cleanup existing tree data before E088/E089 tests. /// /// **Run this before E088 or E089 to ensure clean state.** /// /// Uses SoftDeleteAsync: the objects are re-parented under the trash scheme synchronously, /// so they vanish from queries (and release their unique keys) immediately - clean state /// without waiting. The physical purge of the _values cascade is queued in the database /// and drained by the built-in BackgroundDeletionService in any host that runs it. /// [ExampleMeta("E087", "Tree Cleanup - Remove All", "Trees", ExampleTier.Free, 1, "Tree", "Cleanup", "SoftDeleteAsync", "Pro", Order = 87)] public class E087_TreeCleanup : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var existing = await redb.TreeQuery().ToListAsync(); var count = existing.Count; if (count > 0) { Console.WriteLine($"[E087] Soft-deleting {count} tree nodes..."); // One fast, atomic mark - no waiting for the physical purge. The next examples // see a clean tree right away; the deferred purge work stays queued in the // database (the DB is the queue), invisible to queries either way. var mark = await redb.SoftDeleteAsync(existing.Select(e => e.Id).ToList()); Console.WriteLine( $"[E087] Done: {mark.MarkedCount} nodes moved to trash container {mark.TrashId}; " + "physical purge is queued for the background deletion service."); } sw.Stop(); return Ok("E087", "Tree Cleanup - Remove All", ExampleTier.Free, sw.ElapsedMilliseconds, count, [count > 0 ? $"Soft-deleted: {count} tree nodes (physical purge deferred)" : "No tree data to delete"]); } } Path: redb/redb.Examples/Examples/E088_TreeCreateBulk.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E088_TreeCreateBulk.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// BULK create tree hierarchy (Pro feature) - FAST version. /// /// Creates ~100 tree nodes using pre-generated IDs + AddNewObjectsAsync. /// Compare with E089 (sequential CreateChildAsync). /// /// Structure: /// - 1 root (TechCorp) /// - 10 regional offices /// - 50 departments (5 per office) /// - 40 teams (4 per first 10 departments) /// /// Optimization: /// - **NextObjectIdBatchAsync** - get all IDs in 1 query /// - **AddNewObjectsAsync** - bulk insert all nodes in 1 operation /// [ExampleMeta("E088", "Tree Create BULK - Fast", "Trees", ExampleTier.Free, 3, "Tree", "Bulk", "AddNewObjectsAsync", "Pro", Order = 88)] public class E088_TreeCreateBulk : ExampleBase { internal const int OfficeCount = 10; internal const int DeptPerOffice = 5; internal const int TeamsForFirstDepts = 10; // Teams only for first 10 departments internal const int TeamsPerDept = 4; // Total: 1 + 10 + 50 + 40 = 101 nodes public override async Task RunAsync(IRedbService redb) { // Run E087 first to cleanup existing data var totalNodes = 1 + OfficeCount + (OfficeCount * DeptPerOffice) + (TeamsForFirstDepts * TeamsPerDept); // Measure bulk creation var sw = Stopwatch.StartNew(); // 1. Get all IDs in ONE query var ids = await redb.Context.NextObjectIdBatchAsync(totalNodes); // 2. Create all objects with pre-assigned IDs and parent_id var nodes = GenerateTree(ids); // 3. Bulk insert ALL nodes in ONE operation await redb.AddNewObjectsAsync(nodes.Cast>().ToList()); sw.Stop(); var rate = nodes.Count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1); return Ok("E088", "Tree Create BULK - Fast", ExampleTier.Free, sw.ElapsedMilliseconds, nodes.Count, [$"Bulk created: {nodes.Count} tree nodes in 4 levels", $"Rate: {rate} nodes/sec"]); } /// Generates tree with ~100 nodes using pre-assigned IDs. private static List> GenerateTree(long[] ids) { var nodes = new List>(); var idx = 0; // Level 0: Root var rootId = ids[idx++]; nodes.Add(CreateNode(rootId, null, "TechCorp", "CORP", "Headquarters", 50_000_000m)); // Level 1: Regional offices var officeIds = new long[OfficeCount]; for (int i = 0; i < OfficeCount; i++) { officeIds[i] = ids[idx++]; var city = Cities[i % Cities.Length]; nodes.Add(CreateNode(officeIds[i], rootId, $"{city} Office", $"OFF-{i + 1:D2}", $"Regional office {city}", 5_000_000m - i * 200_000m)); } // Level 2: Departments in each office var deptIds = new List(); for (int o = 0; o < OfficeCount; o++) { for (int d = 0; d < DeptPerOffice; d++) { var deptId = ids[idx++]; deptIds.Add(deptId); var deptName = Departments[d % Departments.Length]; nodes.Add(CreateNode(deptId, officeIds[o], $"{deptName} {o + 1}-{d + 1}", $"DEPT-{o + 1:D2}-{d + 1:D2}", deptName, 1_000_000m - d * 100_000m)); } } // Level 3: Teams in first 10 departments for (int d = 0; d < TeamsForFirstDepts && d < deptIds.Count; d++) { for (int t = 0; t < TeamsPerDept; t++) { var teamId = ids[idx++]; var teamName = Teams[t % Teams.Length]; nodes.Add(CreateNode(teamId, deptIds[d], $"{teamName} Team {d + 1}-{t + 1}", $"TEAM-{d + 1:D2}-{t + 1:D2}", teamName, 300_000m - t * 50_000m)); } } return nodes; } internal static readonly string[] Cities = ["Moscow", "SPB", "Kazan", "Novosibirsk", "Yekaterinburg", "Nizhny", "Samara", "Omsk", "Chelyabinsk", "Rostov"]; internal static readonly string[] Departments = ["IT", "Sales", "HR", "Finance", "Marketing"]; internal static readonly string[] Teams = ["Alpha", "Beta", "Gamma", "Delta"]; private static TreeRedbObject CreateNode(long id, long? parentId, string name, string code, string desc, decimal budget) => new() { id = id, parent_id = parentId, name = name, Props = new DepartmentProps { Name = name, Code = code, Description = desc, Budget = budget, IsActive = true } }; } Path: redb/redb.Examples/Examples/E089_TreeCreate.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E089_TreeCreate.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Sequential create tree hierarchy - deliberate ANTIPATTERN demo. /// /// This example is SLOW BY DESIGN: it saves ~100 tree nodes one CreateChildAsync at a time, /// paying a full save pipeline (key allocation, hash, values insert, commit) per node, to give /// E088 (bulk AddNewObjectsAsync, one round-trip for the whole level) a baseline to beat. /// Do NOT copy this shape into application code - use the bulk API of E088. /// /// Structure: /// - 1 root (TechCorp) /// - 10 regional offices /// - 50 departments (5 per office) /// - 40 teams (4 per first 10 departments) /// [ExampleMeta("E089", "Tree Create Sequential - ANTIPATTERN (slow by design)", "Trees", ExampleTier.Free, 3, "Tree", "CreateChildAsync", "Sequential", "Antipattern", "Pro", Order = 89)] public class E089_TreeCreate : ExampleBase { private const int OfficeCount = 10; private const int DeptPerOffice = 5; private const int TeamsForFirstDepts = 10; private const int TeamsPerDept = 4; public override async Task RunAsync(IRedbService redb) { // Run E087 first to cleanup existing data // Measure sequential creation var sw = Stopwatch.StartNew(); var count = await CreateTreeSequentially(redb); sw.Stop(); var rate = count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1); Console.WriteLine($"[E089] ANTIPATTERN demo: {count} nodes saved one round-trip each on purpose - compare with E088 (bulk)."); return Ok("E089", "Tree Create Sequential - ANTIPATTERN (slow by design)", ExampleTier.Free, sw.ElapsedMilliseconds, count, [ "ANTIPATTERN: one CreateChildAsync round-trip per node, slow on purpose.", $"Sequential created: {count} tree nodes in 4 levels", $"Rate: {rate} nodes/sec - compare with E088 (bulk AddNewObjectsAsync)" ]); } /// Creates tree using sequential CreateChildAsync calls. private static async Task CreateTreeSequentially(IRedbService redb) { var count = 0; // Level 0: Root var root = CreateDept("TechCorp", "CORP", "Headquarters", 50_000_000m); root.id = await redb.SaveAsync(root); count++; // Level 1: Regional offices var offices = new TreeRedbObject[OfficeCount]; for (int i = 0; i < OfficeCount; i++) { var city = Cities[i % Cities.Length]; offices[i] = CreateDept($"{city} Office", $"OFF-{i + 1:D2}", $"Regional office {city}", 5_000_000m - i * 200_000m); offices[i].id = await redb.CreateChildAsync(offices[i], root); count++; } // Level 2: Departments in each office var depts = new List>(); for (int o = 0; o < OfficeCount; o++) { for (int d = 0; d < DeptPerOffice; d++) { var deptName = Departments[d % Departments.Length]; var dept = CreateDept($"{deptName} {o + 1}-{d + 1}", $"DEPT-{o + 1:D2}-{d + 1:D2}", deptName, 1_000_000m - d * 100_000m); dept.id = await redb.CreateChildAsync(dept, offices[o]); depts.Add(dept); count++; } } // Level 3: Teams in first 10 departments for (int d = 0; d < TeamsForFirstDepts && d < depts.Count; d++) { for (int t = 0; t < TeamsPerDept; t++) { var teamName = Teams[t % Teams.Length]; var team = CreateDept($"{teamName} Team {d + 1}-{t + 1}", $"TEAM-{d + 1:D2}-{t + 1:D2}", teamName, 300_000m - t * 50_000m); await redb.CreateChildAsync(team, depts[d]); count++; } } return count; } private static readonly string[] Cities = ["Moscow", "SPB", "Kazan", "Novosibirsk", "Yekaterinburg", "Nizhny", "Samara", "Omsk", "Chelyabinsk", "Rostov"]; private static readonly string[] Departments = ["IT", "Sales", "HR", "Finance", "Marketing"]; private static readonly string[] Teams = ["Alpha", "Beta", "Gamma", "Delta"]; private static TreeRedbObject CreateDept(string name, string code, string desc, decimal budget) => new() { name = name, Props = new DepartmentProps { Name = name, Code = code, Description = desc, Budget = budget, IsActive = true } }; } Path: redb/redb.Examples/Examples/E090_TreeLoad.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E090_TreeLoad.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Load full tree with LoadTreeAsync. /// /// **Requires E089 to run first (creates tree data).** /// /// Loads entire hierarchy from root with specified depth. /// [ExampleMeta("E090", "Tree Load - Full Hierarchy", "Trees", ExampleTier.Free, 2, "Tree", "LoadTreeAsync", "Hierarchy", "Pro", Order = 90, RelatedApis = ["IRedbService.LoadTreeAsync", "TreeRedbObject"])] public class E090_TreeLoad : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find root var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) return Fail("E090", "Tree Load - Full Hierarchy", ExampleTier.Free, 0, "No tree. Run E089 first."); var root = (TreeRedbObject)roots[0]; // Measure LoadTreeAsync var sw = Stopwatch.StartNew(); var tree = await redb.LoadTreeAsync(root, maxDepth: 5); sw.Stop(); var nodeCount = CountNodes(tree); return Ok("E090", "Tree Load - Full Hierarchy", ExampleTier.Free, sw.ElapsedMilliseconds, nodeCount, [$"Root: {tree.name}, Children: {tree.Children.Count}", $"Total nodes loaded: {nodeCount}"]); } private static int CountNodes(ITreeRedbObject node) { var count = 1; foreach (var child in node.Children.OfType>()) count += CountNodes(child); return count; } } Path: redb/redb.Examples/Examples/E091_TreeCount.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E091_TreeCount.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Count tree nodes with TreeQuery. /// /// **Requires E089 to run first (creates tree data).** /// /// CountAsync on TreeQuery - counts all nodes in tree. /// [ExampleMeta("E091", "Tree Count - CountAsync", "Trees", ExampleTier.Free, 1, "Tree", "TreeQuery", "CountAsync", "Pro", Order = 91)] public class E091_TreeCount : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var count = await redb.TreeQuery().CountAsync(); sw.Stop(); if (count == 0) return Fail("E091", "Tree Count - CountAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree. Run E089 first."); return Ok("E091", "Tree Count - CountAsync", ExampleTier.Free, sw.ElapsedMilliseconds, count, [$"TreeQuery().CountAsync()", $"Total: {count} nodes"]); } } Path: redb/redb.Examples/Examples/E092_TreeChildren.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E092_TreeChildren.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Get direct children of a node. /// Uses GetChildrenAsync - returns only immediate children, not descendants. /// [ExampleMeta("E092", "Tree Children - Direct", "Trees", ExampleTier.Free, 2, "Tree", "GetChildrenAsync", "Pro")] public class E092_TreeChildren : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find TechCorp root - use TreeQuery for tree objects! var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) { return Ok("E092", "Tree Children - Direct", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No tree found. Run E090 first."]); } var root = (TreeRedbObject)roots[0]; // Get direct children only var children = await redb.GetChildrenAsync(root); var childList = children.ToList(); sw.Stop(); var names = childList.Select(c => c.Name).ToArray(); return Ok("E092", "Tree Children - Direct", ExampleTier.Free, sw.ElapsedMilliseconds, childList.Count, [ $"Parent: {root.Name} ({root.Props.Code})", $"Children: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/Examples/E093_TreePath.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E093_TreePath.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Get path from node to root. /// Builds breadcrumbs: Team > Department > Office > TechCorp. /// [ExampleMeta("E093", "Tree Path - Breadcrumbs", "Trees", ExampleTier.Free, 2, "Tree", "GetPathToRootAsync", "Breadcrumbs", "Pro")] public class E093_TreePath : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find deepest node (any team at level 3) - use TreeQuery! var nodes = await redb.TreeQuery() .Where(d => d.Code.StartsWith("TEAM-")) .Take(1) .ToListAsync(); if (nodes.Count == 0) { return Ok("E093", "Tree Path - Breadcrumbs", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No tree found. Run E088 or E089 first."]); } var node = (TreeRedbObject)nodes[0]; // Get path to root (returns: DevAlpha, IT-MSK, Moscow, TechCorp) var path = await redb.GetPathToRootAsync(node); var pathList = path.ToList(); sw.Stop(); var breadcrumbs = string.Join(" > ", pathList.Select(n => n.Name)); return Ok("E093", "Tree Path - Breadcrumbs", ExampleTier.Free, sw.ElapsedMilliseconds, pathList.Count, [ $"From: {node.name}", $"Path: {breadcrumbs}", $"Levels: {pathList.Count}" ]); } } Path: redb/redb.Examples/Examples/E094_TreeDescendants.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E094_TreeDescendants.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Get all descendants of a node. /// Returns all children, grandchildren, etc. recursively. /// [ExampleMeta("E094", "Tree Descendants - All", "Trees", ExampleTier.Free, 2, "Tree", "GetDescendantsAsync", "Recursive", "Pro")] public class E094_TreeDescendants : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find TechCorp root - use TreeQuery! var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) { return Ok("E094", "Tree Descendants - All", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No tree found. Run E090 first."]); } var root = (TreeRedbObject)roots[0]; // Get ALL descendants (children, grandchildren, etc.) var descendants = await redb.GetDescendantsAsync(root); var list = descendants.ToList(); sw.Stop(); // Group by level var byLevel = list.GroupBy(d => d.Level).OrderBy(g => g.Key).ToList(); var output = byLevel.Select(g => $"Level {g.Key}: {string.Join(", ", g.Select(d => d.Props.Code))}").ToList(); output.Insert(0, $"Root: {root.Name}, Total descendants: {list.Count}"); return Ok("E094", "Tree Descendants - All", ExampleTier.Free, sw.ElapsedMilliseconds, list.Count, output.ToArray()); } } Path: redb/redb.Examples/Examples/E095_TreeMove.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E095_TreeMove.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Move node to new parent. /// Demonstrates MoveObjectAsync - moves entire subtree. /// [ExampleMeta("E095", "Tree Move - Relocate Node", "Trees", ExampleTier.Free, 3, "Tree", "MoveObjectAsync", "Pro")] public class E095_TreeMove : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find a department to move - use TreeQuery! var nodes = await redb.TreeQuery() .Where(d => d.Code.StartsWith("DEPT-01-")) .Take(1) .ToListAsync(); if (nodes.Count == 0) { return Ok("E095", "Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No tree found. Run E088 or E089 first."]); } // Find another office as new parent - use TreeQuery! var officeNodes = await redb.TreeQuery() .Where(d => d.Code == "OFF-02") .Take(1) .ToListAsync(); if (officeNodes.Count == 0) { return Ok("E095", "Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["Target office not found."]); } var dept = (TreeRedbObject)nodes[0]; var targetOffice = (TreeRedbObject)officeNodes[0]; var originalParentId = dept.parent_id; // Move department to another office await redb.MoveObjectAsync(dept, targetOffice); // Move back to original parent if (originalParentId.HasValue) { var originalParent = await redb.TreeQuery() .Where(d => d.Code == "OFF-01") .Take(1) .ToListAsync(); if (originalParent.Count > 0) { var origOffice = (TreeRedbObject)originalParent[0]; await redb.MoveObjectAsync(dept, origOffice); } } sw.Stop(); return Ok("E095", "Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [ $"Moved: {dept.name} to {targetOffice.name}", "Moved back to original office", "Subtree preserved during move" ]); } } Path: redb/redb.Examples/Examples/E096_TreeQuery.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E096_TreeQuery.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// LINQ queries on tree structures. /// TreeQuery combines tree traversal with Where/OrderBy/Take. /// [ExampleMeta("E096", "Tree Query - LINQ on Trees", "Trees", ExampleTier.Free, 3, "Tree", "TreeQuery", "Where", "OrderBy", "Pro")] public class E096_TreeQuery : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // TreeQuery: find all IT departments var itDepts = await redb.TreeQuery() .Where(d => d.Name.Contains("IT")) .OrderBy(d => d.Name) .ToListAsync(); // var sql = await redb.TreeQuery() // .Where(d => d.Name.Contains("IT")) // .ToSqlStringAsync(); // Console.WriteLine(sql); sw.Stop(); var names = itDepts.Select(d => $"{d.Name} ({d.Props.Code})").ToArray(); return Ok("E096", "Tree Query - LINQ on Trees", ExampleTier.Free, sw.ElapsedMilliseconds, itDepts.Count, [ "Filter: Name.Contains('IT')", $"Found: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/Examples/E097_TreeQueryRoots.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E097_TreeQueryRoots.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Find root nodes in tree. /// WhereRoots returns only top-level nodes (parent_id = null). /// [ExampleMeta("E097", "Tree Query - Roots Only", "Trees", ExampleTier.Free, 2, "Tree", "TreeQuery", "WhereRoots", "Pro", RelatedApis = ["ITreeQueryable.WhereRoots", "IRedbService.TreeQuery"])] public class E097_TreeQueryRoots : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find all root nodes var roots = await redb.TreeQuery() .WhereRoots() .ToListAsync(); sw.Stop(); var names = roots.Select(r => $"{r.Name} ({r.Props.Code})").ToArray(); return Ok("E097", "Tree Query - Roots Only", ExampleTier.Free, sw.ElapsedMilliseconds, roots.Count, [ "Filter: WhereRoots() - parent_id IS NULL", $"Found: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/Examples/E098_TreeQueryLeaves.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E098_TreeQueryLeaves.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Find leaf nodes in tree. /// WhereLeaves returns nodes with no children. /// [ExampleMeta("E098", "Tree Query - Leaves Only", "Trees", ExampleTier.Free, 2, "Tree", "TreeQuery", "WhereLeaves", "Pro")] public class E098_TreeQueryLeaves : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find all leaf nodes (no children) var leaves = await redb.TreeQuery() .WhereLeaves() .ToListAsync(); sw.Stop(); var names = leaves.Select(l => $"{l.Name} ({l.Props.Code})").ToArray(); return Ok("E098", "Tree Query - Leaves Only", ExampleTier.Free, sw.ElapsedMilliseconds, leaves.Count, [ "Filter: WhereLeaves() - no children", $"Found: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/Examples/E099_TreeQueryLevel.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E099_TreeQueryLevel.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter tree nodes by level. /// WhereLevel finds nodes at specific depth from root. /// [ExampleMeta("E099", "Tree Query - By Level", "Trees", ExampleTier.Free, 2, "Tree", "TreeQuery", "WhereLevel", "Pro")] public class E099_TreeQueryLevel : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find root first - use TreeQuery! var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) { return Ok("E099", "Tree Query - By Level", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No tree found. Run E090 first."]); } var rootId = roots[0].Id; var query = redb.TreeQuery(rootId, maxDepth: 5) .WhereLevel(2); //var sql = query.ToSqlString(); //Console.WriteLine(sql); // Find nodes at level 2 (departments under offices) var level2 = await query .WhereLevel(2) .ToListAsync(); sw.Stop(); var names = level2.Select(n => $"{n.Name} ({n.Props.Code})").ToArray(); return Ok("E099", "Tree Query - By Level", ExampleTier.Free, sw.ElapsedMilliseconds, level2.Count, [ "Filter: WhereLevel(2) - departments under offices", $"Found: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/Examples/E100_TreeTraversalDFS.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E100_TreeTraversalDFS.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Utils; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Depth-First traversal of tree. /// Visits nodes: Root -> Child1 -> Grandchild1 -> Grandchild2 -> Child2... /// /// Key method: /// - **tree.DepthFirstTraversal()** - iterate nodes depth-first /// [ExampleMeta("E100", "Tree Traversal - DFS", "Trees", ExampleTier.Free, 2, "Tree", "DepthFirstTraversal", "DFS", "Pro", Order = 100)] public class E100_TreeTraversalDFS : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find root var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) return Fail("E100", "Tree Traversal - DFS", ExampleTier.Free, 0, "No tree. Run E088 first."); var root = (TreeRedbObject)roots[0]; // Load full tree with Children populated var tree = await redb.LoadTreeAsync(root, maxDepth: 5); // Measure DFS traversal (cast to interface for extension method) var sw = Stopwatch.StartNew(); var visited = ((ITreeRedbObject)tree).DepthFirstTraversal().ToList(); sw.Stop(); var sample = visited.Take(5).Select(n => n.Props.Code).ToArray(); return Ok("E100", "Tree Traversal - DFS", ExampleTier.Free, sw.ElapsedMilliseconds, visited.Count, [$"DFS order (first 5): {string.Join(" -> ", sample)}", $"Total visited: {visited.Count}"]); } } Path: redb/redb.Examples/Examples/E101_TreeTraversalBFS.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E101_TreeTraversalBFS.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Utils; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Breadth-First traversal of tree. /// Visits nodes level by level: Root -> All Level1 -> All Level2... /// /// Key method: /// - **tree.BreadthFirstTraversal()** - iterate nodes breadth-first /// [ExampleMeta("E101", "Tree Traversal - BFS", "Trees", ExampleTier.Free, 2, "Tree", "BreadthFirstTraversal", "BFS", "Pro", Order = 101)] public class E101_TreeTraversalBFS : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find root var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) return Fail("E101", "Tree Traversal - BFS", ExampleTier.Free, 0, "No tree. Run E088 first."); var root = (TreeRedbObject)roots[0]; // Load full tree with Children populated var tree = await redb.LoadTreeAsync(root, maxDepth: 5); // Measure BFS traversal (cast to interface for extension method) var sw = Stopwatch.StartNew(); var visited = ((ITreeRedbObject)tree).BreadthFirstTraversal().ToList(); sw.Stop(); // Group by level var byLevel = visited.GroupBy(n => n.Level).OrderBy(g => g.Key); var levelCounts = byLevel.Select(g => $"L{g.Key}:{g.Count()}").ToArray(); return Ok("E101", "Tree Traversal - BFS", ExampleTier.Free, sw.ElapsedMilliseconds, visited.Count, [$"BFS by level: {string.Join(", ", levelCounts)}", $"Total visited: {visited.Count}"]); } } Path: redb/redb.Examples/Examples/E102_TreeIsDescendant.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E102_TreeIsDescendant.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Extensions; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Check if node is descendant of another. /// IsDescendantOfAsync - optimized check without loading full tree. /// [ExampleMeta("E102", "Tree - IsDescendantOf", "Trees", ExampleTier.Free, 2, "Tree", "IsDescendantOfAsync", "Pro", Order = 102)] public class E102_TreeIsDescendant : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find root and a deep node var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); var teams = await redb.TreeQuery() .Where(d => d.Code.StartsWith("TEAM-")) .Take(1) .ToListAsync(); if (roots.Count == 0 || teams.Count == 0) return Fail("E102", "Tree - IsDescendantOf", ExampleTier.Free, 0, "No tree. Run E088 first."); var root = roots[0]; var team = teams[0]; // Check if team is descendant of root var sw = Stopwatch.StartNew(); var isDescendant = await team.IsDescendantOfAsync(root, redb); var isNotDescendant = await root.IsDescendantOfAsync(team, redb); sw.Stop(); return Ok("E102", "Tree - IsDescendantOf", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [ $"{team.Props.Code} descendant of {root.Props.Code}: {isDescendant}", $"{root.Props.Code} descendant of {team.Props.Code}: {isNotDescendant}" ]); } } Path: redb/redb.Examples/Examples/E103_TreeIsAncestor.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E103_TreeIsAncestor.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Extensions; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Check if node is ancestor of another. /// IsAncestorOfAsync - checks if this node is parent/grandparent of target. /// [ExampleMeta("E103", "Tree - IsAncestorOf", "Trees", ExampleTier.Free, 2, "Tree", "IsAncestorOfAsync", "Pro", Order = 103)] public class E103_TreeIsAncestor : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find root and a deep node var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); var teams = await redb.TreeQuery() .Where(d => d.Code.StartsWith("TEAM-")) .Take(1) .ToListAsync(); if (roots.Count == 0 || teams.Count == 0) return Fail("E103", "Tree - IsAncestorOf", ExampleTier.Free, 0, "No tree. Run E088 first."); var root = roots[0]; var team = teams[0]; // Check if root is ancestor of team var sw = Stopwatch.StartNew(); var isAncestor = await root.IsAncestorOfAsync(team, redb); var isNotAncestor = await team.IsAncestorOfAsync(root, redb); sw.Stop(); return Ok("E103", "Tree - IsAncestorOf", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [ $"{root.Props.Code} ancestor of {team.Props.Code}: {isAncestor}", $"{team.Props.Code} ancestor of {root.Props.Code}: {isNotAncestor}" ]); } } Path: redb/redb.Examples/Examples/E104_TreeGetLevel.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E104_TreeGetLevel.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Extensions; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Get tree level of a node. /// GetTreeLevelAsync - counts levels from root (root = 0). /// [ExampleMeta("E104", "Tree - GetLevel", "Trees", ExampleTier.Free, 2, "Tree", "GetTreeLevelAsync", "Pro", Order = 104)] public class E104_TreeGetLevel : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find nodes at different levels var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); var offices = await redb.TreeQuery() .Where(d => d.Code == "OFF-01") .Take(1) .ToListAsync(); var teams = await redb.TreeQuery() .Where(d => d.Code.StartsWith("TEAM-")) .Take(1) .ToListAsync(); if (roots.Count == 0) return Fail("E104", "Tree - GetLevel", ExampleTier.Free, 0, "No tree. Run E088 first."); var sw = Stopwatch.StartNew(); var rootLevel = await roots[0].GetTreeLevelAsync(redb); var officeLevel = offices.Count > 0 ? await offices[0].GetTreeLevelAsync(redb) : -1; var teamLevel = teams.Count > 0 ? await teams[0].GetTreeLevelAsync(redb) : -1; sw.Stop(); return Ok("E104", "Tree - GetLevel", ExampleTier.Free, sw.ElapsedMilliseconds, 3, [ $"Root (CORP): level {rootLevel}", $"Office (OFF-01): level {officeLevel}", $"Team: level {teamLevel}" ]); } } Path: redb/redb.Examples/Examples/E105_TreeQueryWithRoot.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E105_TreeQueryWithRoot.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// TreeQuery scoped to specific root. /// TreeQuery(rootId, maxDepth) - queries only within subtree. /// [ExampleMeta("E105", "Tree Query - Scoped to Root", "Trees", ExampleTier.Free, 2, "Tree", "TreeQuery", "RootId", "Pro", Order = 105)] public class E105_TreeQueryWithRoot : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find an office to use as root var offices = await redb.TreeQuery() .Where(d => d.Code == "OFF-01") .Take(1) .ToListAsync(); if (offices.Count == 0) return Fail("E105", "Tree Query - Scoped to Root", ExampleTier.Free, 0, "No tree. Run E088 first."); var officeId = offices[0].Id; // Query only within this office's subtree var sw = Stopwatch.StartNew(); var subtreeNodes = await redb.TreeQuery(officeId, maxDepth: 3) .ToListAsync(); sw.Stop(); var codes = subtreeNodes.Take(5).Select(n => n.Props.Code).ToArray(); return Ok("E105", "Tree Query - Scoped to Root", ExampleTier.Free, sw.ElapsedMilliseconds, subtreeNodes.Count, [ $"Subtree of OFF-01: {subtreeNodes.Count} nodes", $"Sample: {string.Join(", ", codes)}" ]); } } Path: redb/redb.Examples/Examples/E106_TreeQueryChildrenOf.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E106_TreeQueryChildrenOf.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query direct children of a node. /// WhereChildrenOf(parentId) - returns only immediate children. /// [ExampleMeta("E106", "Tree Query - WhereChildrenOf", "Trees", ExampleTier.Free, 2, "Tree", "TreeQuery", "WhereChildrenOf", "Pro", Order = 106)] public class E106_TreeQueryChildrenOf : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find root var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) return Fail("E106", "Tree Query - WhereChildrenOf", ExampleTier.Free, 0, "No tree. Run E088 first."); var rootId = roots[0].Id; // Get direct children only var sw = Stopwatch.StartNew(); var children = await redb.TreeQuery() .WhereChildrenOf(rootId) .ToListAsync(); sw.Stop(); var names = children.Take(5).Select(c => c.Props.Code).ToArray(); return Ok("E106", "Tree Query - WhereChildrenOf", ExampleTier.Free, sw.ElapsedMilliseconds, children.Count, [ $"Direct children of CORP: {children.Count}", $"Codes: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/Examples/E107_TreeQueryMultiRoot.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E107_TreeQueryMultiRoot.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// TreeQuery with multiple root parents. /// TreeQuery(parents[], maxDepth) - queries across multiple subtrees. /// [ExampleMeta("E107", "Tree Query - Multiple Roots", "Trees", ExampleTier.Free, 3, "Tree", "TreeQuery", "MultiRoot", "Pro", Order = 107)] public class E107_TreeQueryMultiRoot : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find two offices to use as roots var office1 = await redb.TreeQuery() .Where(d => d.Code == "OFF-01") .Take(1) .ToListAsync(); var office2 = await redb.TreeQuery() .Where(d => d.Code == "OFF-02") .Take(1) .ToListAsync(); if (office1.Count == 0 || office2.Count == 0) return Fail("E107", "Tree Query - Multiple Roots", ExampleTier.Free, 0, "No tree. Run E088 first."); var parents = new IRedbObject[] { office1[0], office2[0] }; // Query across both subtrees var sw = Stopwatch.StartNew(); var results = await redb.TreeQuery(parents, maxDepth: 3) .ToListAsync(); sw.Stop(); var byParent = results.GroupBy(r => r.ParentId).Select(g => $"{g.Key}:{g.Count()}").ToArray(); return Ok("E107", "Tree Query - Multiple Roots", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [ $"Nodes in OFF-01 + OFF-02 subtrees: {results.Count}", $"By parent: {string.Join(", ", byParent.Take(3))}" ]); } } Path: redb/redb.Examples/Examples/E108_TreeToTreeList.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E108_TreeToTreeList.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// ToTreeListAsync with Parent chain. /// Returns nodes with Parent property populated up to root. /// [ExampleMeta("E108", "Tree Query - ToTreeListAsync", "Trees", ExampleTier.Free, 3, "Tree", "ToTreeListAsync", "ParentChain", "Pro", Order = 108)] public class E108_TreeToTreeList : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Query teams (deep nodes) var sw = Stopwatch.StartNew(); var teams = await redb.TreeQuery() .Where(d => d.Code.StartsWith("TEAM-")) .Take(5) .ToTreeListAsync(); sw.Stop(); if (teams.Count == 0) return Fail("E108", "Tree Query - ToTreeListAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree. Run E088 first."); // Check parent chain var first = teams[0]; var parentDepth = 0; var current = first.Parent; while (current != null && parentDepth < 10) { parentDepth++; current = (current as TreeRedbObject)?.Parent; } return Ok("E108", "Tree Query - ToTreeListAsync", ExampleTier.Free, sw.ElapsedMilliseconds, teams.Count, [ $"Loaded: {teams.Count} teams with Parent chain", $"First team parent depth: {parentDepth} levels to root" ]); } } Path: redb/redb.Examples/Examples/E109_TreeToRootList.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E109_TreeToRootList.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// ToRootListAsync - get full tree structure. /// Returns root nodes with Children populated recursively. /// [ExampleMeta("E109", "Tree Query - ToRootListAsync", "Trees", ExampleTier.Free, 3, "Tree", "ToRootListAsync", "FullTree", "Pro", Order = 109)] public class E109_TreeToRootList : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Get full tree from roots var sw = Stopwatch.StartNew(); var rootTrees = await redb.TreeQuery() .WhereRoots() .ToRootListAsync(); sw.Stop(); if (rootTrees.Count == 0) return Fail("E109", "Tree Query - ToRootListAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree. Run E088 first."); // Count total nodes in tree var totalNodes = CountNodes(rootTrees[0]); return Ok("E109", "Tree Query - ToRootListAsync", ExampleTier.Free, sw.ElapsedMilliseconds, totalNodes, [ $"Root trees: {rootTrees.Count}", $"First tree total nodes: {totalNodes}" ]); } private static int CountNodes(ITreeRedbObject node) { var count = 1; foreach (var child in node.Children) count += CountNodes(child); return count; } } Path: redb/redb.Examples/Examples/E110_TreeWhereHasAncestor.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E110_TreeWhereHasAncestor.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// WhereHasAncestor - polymorphic ancestor filter. /// Find nodes that have a specific type of ancestor matching condition. /// [ExampleMeta("E110", "Tree Query - WhereHasAncestor", "Trees", ExampleTier.Free, 3, "Tree", "WhereHasAncestor", "Polymorphic", "Pro", Order = 110, RelatedApis = ["ITreeQueryable.WhereHasAncestor"])] public class E110_TreeWhereHasAncestor : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find teams that have an ancestor with Budget > 500000 (decimal test!) var sw = Stopwatch.StartNew(); var teams = await redb.TreeQuery() .Where(d => d.Code.StartsWith("TEAM-")) .WhereHasAncestor(anc => anc.Budget > 500000m) .ToListAsync(); sw.Stop(); var codes = teams.Take(5).Select(t => t.Props.Code).ToArray(); return Ok("E110", "Tree Query - WhereHasAncestor", ExampleTier.Free, sw.ElapsedMilliseconds, teams.Count, [ $"Teams with rich ancestors (budget > 500k): {teams.Count}", $"Sample: {string.Join(", ", codes)}" ]); } } Path: redb/redb.Examples/Examples/E111_TreeWhereHasDescendant.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E111_TreeWhereHasDescendant.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// WhereHasDescendant - find parents by child criteria. /// Find offices that have active departments beneath them. /// [ExampleMeta("E111", "Tree Query - WhereHasDescendant", "Trees", ExampleTier.Free, 3, "Tree", "WhereHasDescendant", "Polymorphic", "Pro", Order = 111)] public class E111_TreeWhereHasDescendant : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find offices that have descendants with Budget > 100000 (decimal test!) var sw = Stopwatch.StartNew(); var offices = await redb.TreeQuery() .Where(d => d.Code.StartsWith("OFF-")) .WhereHasDescendant(desc => desc.Budget > 100000m) .ToListAsync(); sw.Stop(); var codes = offices.Take(5).Select(o => o.Props.Code).ToArray(); return Ok("E111", "Tree Query - WhereHasDescendant", ExampleTier.Free, sw.ElapsedMilliseconds, offices.Count, [ $"Offices with rich descendants (budget > 100k): {offices.Count}", $"Sample: {string.Join(", ", codes)}" ]); } } Path: redb/redb.Examples/Examples/E112_TreeStats.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E112_TreeStats.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Models.Collections; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Tree statistics via TreeCollection. /// TreeCollection.GetStats() - node count, depth, leaf count, max width. /// /// Key method: /// - **collection.GetStats()** - get tree metrics /// [ExampleMeta("E112", "Tree - GetStats", "Trees", ExampleTier.Free, 2, "Tree", "TreeCollection", "GetStats", "Statistics", "Pro", Order = 112)] public class E112_TreeStats : ExampleBase { public override async Task RunAsync(IRedbService redb) { // Find root var roots = await redb.TreeQuery() .Where(d => d.Code == "CORP") .Take(1) .ToListAsync(); if (roots.Count == 0) return Fail("E112", "Tree - GetStats", ExampleTier.Free, 0, "No tree. Run E088 first."); var root = (TreeRedbObject)roots[0]; // Load tree and build collection var sw = Stopwatch.StartNew(); var tree = await redb.LoadTreeAsync(root, maxDepth: 5); // Build TreeCollection for stats var collection = new TreeCollection(); AddToCollection(collection, tree); var stats = collection.GetStats(); sw.Stop(); return Ok("E112", "Tree - GetStats", ExampleTier.Free, sw.ElapsedMilliseconds, collection.Count, [$"Stats: {stats}", $"Collection count: {collection.Count}"]); } private static void AddToCollection(TreeCollection collection, ITreeRedbObject node) { collection.Add(node); foreach (var child in node.Children.OfType>()) AddToCollection(collection, child); } } Path: redb/redb.Examples/Examples/E113_TreeToFlatList.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E113_TreeToFlatList.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Load tree nodes as flat list without Parent/Children links. /// ToFlatListAsync is faster than ToTreeListAsync - skips relationship building. /// Requires E089 to run first (creates tree data). /// [ExampleMeta("E113", "Tree Query - ToFlatListAsync", "Trees", ExampleTier.Free, 113, "ToFlatListAsync", "Tree", "Flat", "Performance", RelatedApis = ["ITreeQueryable.ToFlatListAsync"])] public class E113_TreeToFlatList : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Load root department var root = await redb.TreeQuery() .WhereRoots() .Take(1) .ToListAsync(); if (root.Count == 0) { sw.Stop(); return Fail("E113", "Tree Query - ToFlatListAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree found. Run E089 first."); } // Load tree as flat list (no Parent/Children links) var query = redb.TreeQuery(root[0].Id, maxDepth: 3) .Where(d => d.IsActive); // Uncomment to see generated SQL: //var sql = await query.ToSqlStringAsync(); //Console.WriteLine(sql); var flatList = await query.ToFlatListAsync(); sw.Stop(); var sample = flatList.FirstOrDefault()?.Props.Name ?? "N/A"; return Ok("E113", "Tree Query - ToFlatListAsync", ExampleTier.Free, sw.ElapsedMilliseconds, flatList.Count, [$"Flat list: {flatList.Count} nodes", $"First: {sample}"]); } } Path: redb/redb.Examples/Examples/E114_ListCreate.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E114_ListCreate.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Creates a new RedbList (dictionary/lookup table). /// RedbList is used to store reference data like statuses, categories, etc. /// [ExampleMeta("E114", "List - Create", "List", ExampleTier.Free, 114, "List", "Create", "Dictionary", RelatedApis = ["IListProvider.SaveListAsync", "RedbList.Create"])] public class E114_ListCreate : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Check if list already exists and delete it (with FK cleanup) var existing = await redb.ListProvider.GetListByNameAsync("ExampleStatuses"); if (existing != null) { // First delete all _values referencing list items (FK constraint) var items = await redb.ListProvider.GetListItemsAsync(existing.Id); var itemIds = items.Select(i => i.Id).ToList(); if (itemIds.Count > 0) { await redb.Context.Bulk.BulkDeleteValuesByListItemIdsAsync(itemIds); } await redb.ListProvider.DeleteListAsync(existing.Id); } // Create a new list (dictionary) var statusList = RedbList.Create("ExampleStatuses", "Example Statuses"); // Uncomment to see generated SQL: // (Lists use direct ADO.NET, no ORM query) var savedList = await redb.ListProvider.SaveListAsync(statusList); sw.Stop(); return Ok("E114", "List - Create", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"List ID: {savedList.Id}", $"Name: {savedList.Name}", $"Alias: {savedList.Alias ?? "N/A"}"]); } } Path: redb/redb.Examples/Examples/E115_ListAddItems.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E115_ListAddItems.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Adds multiple items to a RedbList using AddItemsAsync. /// Batch operation for efficient bulk insert of list items. /// Requires E114 to run first (creates the list). /// [ExampleMeta("E115", "List - Add Items", "List", ExampleTier.Free, 115, "List", "AddItems", "Batch", RelatedApis = ["IListProvider.AddItemsAsync"])] public class E115_ListAddItems : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get existing list (created in E114) var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E115", "List - Add Items", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114 first."); } // Prepare values and aliases var values = new List { "Active", "Inactive", "Pending", "Blocked" }; var aliases = new List { "Active status", "Inactive status", "Pending review", "Blocked access" }; // Uncomment to see generated SQL: // (Lists use direct ADO.NET, no ORM query) // Batch add items var addedItems = await redb.ListProvider.AddItemsAsync(list, values, aliases); sw.Stop(); var itemsList = string.Join(", ", addedItems.Select(i => i.Value)); return Ok("E115", "List - Add Items", ExampleTier.Free, sw.ElapsedMilliseconds, addedItems.Count, [$"Added: {addedItems.Count} items", $"Values: {itemsList}"]); } } Path: redb/redb.Examples/Examples/E116_ListGetByName.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E116_ListGetByName.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Gets a RedbList by name and retrieves its items. /// Shows how to lookup lists and access their contents. /// Requires E114+E115 to run first. /// [ExampleMeta("E116", "List - Get Items", "List", ExampleTier.Free, 116, "List", "GetByName", "GetItems", RelatedApis = ["IListProvider.GetListByNameAsync", "IListProvider.GetListItemsAsync"])] public class E116_ListGetByName : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get list by name var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E116", "List - Get Items", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114 first."); } // Uncomment to see generated SQL: // (Lists use direct ADO.NET, no ORM query) // Get all items from the list var items = await redb.ListProvider.GetListItemsAsync(list.Id); sw.Stop(); var itemsPreview = string.Join(", ", items.Take(3).Select(i => $"{i.Value}")); if (items.Count > 3) itemsPreview += "..."; return Ok("E116", "List - Get Items", ExampleTier.Free, sw.ElapsedMilliseconds, items.Count, [$"List: {list.Name} (ID: {list.Id})", $"Items: {itemsPreview}"]); } } Path: redb/redb.Examples/Examples/E117_ListItemWithObject.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E117_ListItemWithObject.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Creates a ListItem with linked RedbObject. /// ListItem can reference any object via IdObject property. /// Linked object is loaded lazily via Object property. /// Requires E114+E115 to run first. /// [ExampleMeta("E117", "ListItem - With Object", "List", ExampleTier.Free, 117, "ListItem", "Object", "Reference", RelatedApis = ["IListProvider.SaveListItemAsync", "RedbListItem.Object"])] public class E117_ListItemWithObject : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get existing list var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E117", "ListItem - With Object", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114 first."); } // Create a city object var cityObj = new RedbObject { name = "Moscow", Props = new CityProps { Name = "Moscow", Population = 12_655_000, Region = "Central Federal District", IsCapital = true, Coordinates = [55.7558, 37.6173] } }; var cityId = await redb.SaveAsync(cityObj); // Create a new list item with object reference var item = new RedbListItem(list, "Capital", "Capital city status", cityObj); // Uncomment to see generated SQL: // (Lists use direct ADO.NET, no ORM query) var savedItem = await redb.ListProvider.SaveListItemAsync(item); sw.Stop(); return Ok("E117", "ListItem - With Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Item: {savedItem.Value} (ID: {savedItem.Id})", $"Linked object ID: {savedItem.IdObject}"]); } } Path: redb/redb.Examples/Examples/E118_PropsListItemField.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E118_PropsListItemField.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Caching; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Object with ListItem field in Props. /// Shows how to store reference to list item in object properties. /// Requires E114+E115 to run first. /// [ExampleMeta("E118", "Props - ListItem Field", "List", ExampleTier.Free, 118, "Props", "ListItem", "Field", RelatedApis = ["RedbListItem"])] public class E118_PropsListItemField : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get existing list var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E118", "Props - ListItem Field", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114 first."); } // Get list items var items = await redb.ListProvider.GetListItemsAsync(list.Id); var activeStatus = items.FirstOrDefault(i => i.Value == "Active"); if (activeStatus == null) { sw.Stop(); return Fail("E118", "Props - ListItem Field", ExampleTier.Free, sw.ElapsedMilliseconds, "Item 'Active' not found. Run E115 first."); } // Create person with Status field (ListItem) var person = new RedbObject { name = "John Doe", Props = new PersonProps { Name = "John Doe", Age = 30, Email = "john@example.com", Status = activeStatus // Single ListItem field } }; // Uncomment to see generated SQL: // (Save uses COPY protocol for Pro) var personId = await redb.SaveAsync(person); // Load back to verify redb.PropsCache.Clear(); var loaded = await redb.LoadAsync(personId); sw.Stop(); var statusValue = loaded?.Props?.Status?.Value ?? "N/A"; return Ok("E118", "Props - ListItem Field", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Person ID: {personId}", $"Status: {statusValue}"]); } } Path: redb/redb.Examples/Examples/E119_PropsListItemArray.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E119_PropsListItemArray.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Caching; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Object with List of ListItems field in Props. /// Shows how to store multiple list item references (e.g. roles, tags). /// Requires E114+E115 to run first. /// [ExampleMeta("E119", "Props - List", "List", ExampleTier.Free, 119, "Props", "ListItem", "Array", "Roles", RelatedApis = ["List"])] public class E119_PropsListItemArray : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get existing list var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E119", "Props - List", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114 first."); } // Get list items var items = await redb.ListProvider.GetListItemsAsync(list.Id); if (items.Count < 2) { sw.Stop(); return Fail("E119", "Props - List", ExampleTier.Free, sw.ElapsedMilliseconds, "Need at least 2 items. Run E115 first."); } // Create person with Roles field (List) var person = new RedbObject { name = "Jane Smith", Props = new PersonProps { Name = "Jane Smith", Age = 28, Email = "jane@example.com", Roles = items.Take(3).ToList() // Multiple ListItem references } }; // Uncomment to see generated SQL: // (Save uses COPY protocol for Pro) var personId = await redb.SaveAsync(person); // Load back to verify redb.PropsCache.Clear(); var loaded = await redb.LoadAsync(personId); sw.Stop(); var rolesCount = loaded?.Props?.Roles?.Count ?? 0; var rolesList = loaded?.Props?.Roles != null ? string.Join(", ", loaded.Props.Roles.Select(r => r.Value)) : "N/A"; return Ok("E119", "Props - List", ExampleTier.Free, sw.ElapsedMilliseconds, rolesCount, [$"Person ID: {personId}", $"Roles ({rolesCount}): {rolesList}"]); } } Path: redb/redb.Examples/Examples/E120_ListItemWhereByValue.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E120_ListItemWhereByValue.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query filtering by ListItem.Value property. /// Shows how to filter objects by the Value of a ListItem field. /// Requires E114-E118 to run first. /// [ExampleMeta("E120", "ListItem - Where by Value", "List", ExampleTier.Free, 120, "ListItem", "Where", "Value", "Query", RelatedApis = ["IRedbQueryable.Where", "RedbListItem.Value"])] public class E120_ListItemWhereByValue : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Query persons where Status.Value == "Active" var query = redb.Query() .Where(p => p.Status!.Value == "Active") .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); if (results.Count == 0) { return Ok("E120", "ListItem - Where by Value", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No persons with Status='Active' found", "Run E118 first to create test data"]); } var firstName = results.FirstOrDefault()?.Props?.Name ?? "N/A"; return Ok("E120", "ListItem - Where by Value", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Status.Value == 'Active'", $"Found: {results.Count}, First: {firstName}"]); } } Path: redb/redb.Examples/Examples/E121_ListItemWhereIn.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E121_ListItemWhereIn.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query filtering by ListItem.Value using WhereIn. /// Shows how to filter objects by multiple ListItem values at once. /// Requires E114-E118 to run first. /// [ExampleMeta("E121", "ListItem - WhereIn by Value", "List", ExampleTier.Free, 121, "ListItem", "WhereIn", "Value", "Query", RelatedApis = ["IRedbQueryable.WhereIn", "RedbListItem.Value"])] public class E121_ListItemWhereIn : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Query persons where Status.Value in ["Active", "Pending"] var targetValues = new[] { "Active", "Pending", "Blocked" }; var query = redb.Query() .WhereIn(p => p.Status!.Value, targetValues) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); if (results.Count == 0) { return Ok("E121", "ListItem - WhereIn by Value", ExampleTier.Free, sw.ElapsedMilliseconds, 0, [$"Filter: Status.Value IN [{string.Join(", ", targetValues)}]", "No matching persons found"]); } var statuses = results.Select(r => r.Props?.Status?.Value ?? "N/A").Distinct(); return Ok("E121", "ListItem - WhereIn by Value", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Status.Value IN [{string.Join(", ", targetValues)}]", $"Found statuses: {string.Join(", ", statuses)}"]); } } Path: redb/redb.Examples/Examples/E122_ListItemDirectCompare.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E122_ListItemDirectCompare.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query filtering by direct ListItem comparison. /// Shows how to compare ListItem field with a ListItem instance directly. /// Requires E114-E118 to run first. /// [ExampleMeta("E122", "ListItem - Direct Compare", "List", ExampleTier.Free, 122, "ListItem", "Where", "Compare", "Query", RelatedApis = ["IRedbQueryable.Where", "RedbListItem"])] public class E122_ListItemDirectCompare : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get a ListItem to compare against var list = await redb.ListProvider.GetListByNameAsync("ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E122", "ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114 first."); } var items = await redb.ListProvider.GetListItemsAsync(list.Id); var activeItem = items.FirstOrDefault(i => i.Value == "Active"); if (activeItem == null) { sw.Stop(); return Fail("E122", "ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds, "Item 'Active' not found. Run E115 first."); } // Query persons where Status == activeItem (by ID) var query = redb.Query() .Where(p => p.Status == activeItem) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); return Ok("E122", "ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Status == ListItem(ID:{activeItem.Id})", $"Found: {results.Count} persons"]); } } Path: redb/redb.Examples/Examples/E123_ListItemArrayAny.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E123_ListItemArrayAny.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query filtering by ListItem array using Any(). /// Shows how to filter objects where any element in ListItem array matches condition. /// Requires E114-E119 to run first. /// [ExampleMeta("E123", "ListItem Array - Any", "List", ExampleTier.Free, 123, "ListItem", "Array", "Any", "Query", RelatedApis = ["IRedbQueryable.Where", "List.Any"])] public class E123_ListItemArrayAny : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Query persons where any Role has Value == "Active" var query = redb.Query() .Where(p => p.Roles!.Any(r => r.Value == "Active")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); if (results.Count == 0) { return Ok("E123", "ListItem Array - Any", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["Filter: Roles.Any(r => r.Value == 'Active')", "No matching persons found. Run E119 first."]); } var firstName = results.FirstOrDefault()?.Props?.Name ?? "N/A"; var rolesCount = results.FirstOrDefault()?.Props?.Roles?.Count ?? 0; return Ok("E123", "ListItem Array - Any", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Roles.Any(r => r.Value == 'Active')", $"Found: {results.Count}, First: {firstName} ({rolesCount} roles)"]); } } Path: redb/redb.Examples/Examples/E124_SumAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E124_SumAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Calculates sum of a numeric field using SumAsync. /// Server-side aggregation without loading objects, over a field of the employee and over a field /// two nested classes deep (HomeAddress.Building.Floor). /// [ExampleMeta("E124", "SumAsync - Total", "Analytics", ExampleTier.Free, 124, "Sum", "Aggregation", "Analytics", RelatedApis = ["IRedbQueryable.SumAsync"])] public class E124_SumAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query(); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var totalSalary = await query.SumAsync(e => e.Salary); var totalFloor = await query.SumAsync(e => e.HomeAddress!.Building!.Floor); sw.Stop(); return Ok("E124", "SumAsync - Total", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [$"SUM(Salary) = {totalSalary:N0}", $"SUM(HomeAddress.Building.Floor) = {totalFloor:N0}", "Server-side aggregation"]); } } Path: redb/redb.Examples/Examples/E125_AverageAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E125_AverageAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Calculates average of a numeric field using AverageAsync. /// Server-side aggregation without loading objects, over a field of the employee and over a field /// two nested classes deep (HomeAddress.Building.Floor). /// [ExampleMeta("E125", "AverageAsync - Mean", "Analytics", ExampleTier.Free, 125, "Average", "Avg", "Aggregation", "Analytics", RelatedApis = ["IRedbQueryable.AverageAsync"])] public class E125_AverageAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query(); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var avgAge = await query.AverageAsync(e => e.Age); var avgFloor = await query.AverageAsync(e => e.HomeAddress!.Building!.Floor); sw.Stop(); return Ok("E125", "AverageAsync - Mean", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [$"AVG(Age) = {avgAge:F2}", $"AVG(HomeAddress.Building.Floor) = {avgFloor:F2}", "Server-side aggregation"]); } } Path: redb/redb.Examples/Examples/E126_MinMaxAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E126_MinMaxAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Calculates min and max of numeric fields using MinAsync/MaxAsync. /// Server-side aggregation without loading objects, over a field of the employee and over a field /// two nested classes deep (HomeAddress.Building.Floor). /// [ExampleMeta("E126", "MinAsync/MaxAsync - Range", "Analytics", ExampleTier.Free, 126, "Min", "Max", "Aggregation", "Analytics", RelatedApis = ["IRedbQueryable.MinAsync", "IRedbQueryable.MaxAsync"])] public class E126_MinMaxAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query(); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var minSalary = await query.MinAsync(e => e.Salary); var maxSalary = await query.MaxAsync(e => e.Salary); var minFloor = await query.MinAsync(e => e.HomeAddress!.Building!.Floor); var maxFloor = await query.MaxAsync(e => e.HomeAddress!.Building!.Floor); sw.Stop(); return Ok("E126", "MinAsync/MaxAsync - Range", ExampleTier.Free, sw.ElapsedMilliseconds, 4, [$"MIN(Salary) = {minSalary:N0}", $"MAX(Salary) = {maxSalary:N0}", $"MIN/MAX(HomeAddress.Building.Floor) = {minFloor}..{maxFloor}"]); } } Path: redb/redb.Examples/Examples/E127_AggregateAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E127_AggregateAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Batch aggregation with multiple functions in single query. /// Calculates Sum, Avg, Min, Max, Count in ONE SQL request, over fields of the employee and over a field /// two nested classes deep (HomeAddress.Building.Floor): for redb a nested field is just another structure. /// [ExampleMeta("E127", "AggregateAsync - Batch", "Analytics", ExampleTier.Free, 127, "Aggregate", "Batch", "Sum", "Avg", "Count", RelatedApis = ["IRedbQueryable.AggregateAsync", "Agg.Sum", "Agg.Average", "Agg.Count"])] public class E127_AggregateAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Multiple aggregations in ONE query (Pro PVT-based) var stats = await redb.Query() .AggregateAsync(x => new { TotalSalary = Agg.Sum(x.Props.Salary), AvgAge = Agg.Average(x.Props.Age), MinSalary = Agg.Min(x.Props.Salary), MaxSalary = Agg.Max(x.Props.Salary), MinFloor = Agg.Min(x.Props.HomeAddress!.Building!.Floor), MaxFloor = Agg.Max(x.Props.HomeAddress!.Building!.Floor), AvgFloor = Agg.Average(x.Props.HomeAddress!.Building!.Floor), Count = Agg.Count() }); sw.Stop(); return Ok("E127", "AggregateAsync - Batch", ExampleTier.Free, sw.ElapsedMilliseconds, (int)stats.Count, [$"8 aggregations in 1 query, 3 of them over HomeAddress.Building.Floor", $"Total: {stats.TotalSalary:N0}, Avg Age: {stats.AvgAge:F1}, Count: {stats.Count}", $"Home floor: {stats.MinFloor}..{stats.MaxFloor}, avg {stats.AvgFloor:F1}"]); } } Path: redb/redb.Examples/Examples/E128_GroupBySimple.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E128_GroupBySimple.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Groups objects by a field and calculates aggregates per group. /// SQL: GROUP BY Department with SUM, AVG, COUNT, plus AVG over a field two nested classes deep /// (HomeAddress.Building.Floor). /// [ExampleMeta("E128", "GroupBy - Simple", "Analytics", ExampleTier.Free, 128, "GroupBy", "Aggregation", "Analytics", RelatedApis = ["IRedbQueryable.GroupBy", "IGroupedQueryable.SelectAsync"])] public class E128_GroupBySimple : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Uncomment to see generated SQL: // var sql = await redb.Query() // .GroupBy(x => x.Department) // .ToSqlStringAsync(g => new { Dept = g.Key, Total = Agg.Sum(g, x => x.Salary) }); // Console.WriteLine(sql); var byDept = await redb.Query() .GroupBy(x => x.Department) .SelectAsync(g => new { Department = g.Key, TotalSalary = Agg.Sum(g, x => x.Salary), AvgAge = Agg.Average(g, x => x.Age), AvgFloor = Agg.Average(g, x => x.HomeAddress!.Building!.Floor), Count = Agg.Count(g) }); sw.Stop(); var first = byDept.FirstOrDefault(); return Ok("E128", "GroupBy - Simple", ExampleTier.Free, sw.ElapsedMilliseconds, byDept.Count, [$"Groups: {byDept.Count}", $"First: {first?.Department ?? "N/A"}, Count: {first?.Count ?? 0}, Avg home floor: {first?.AvgFloor:F2}"]); } } Path: redb/redb.Examples/Examples/E129_GroupByFiltered.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E129_GroupByFiltered.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// GroupBy with Where filter applied before grouping. /// Filter employees by salary, then group by department; one aggregate reads a field two nested /// classes deep (HomeAddress.Building.Floor). /// [ExampleMeta("E129", "GroupBy - With Filter", "Analytics", ExampleTier.Free, 129, "GroupBy", "Where", "Filter", "Analytics", RelatedApis = ["IRedbQueryable.GroupBy", "IRedbQueryable.Where"])] public class E129_GroupByFiltered : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Uncomment to see generated SQL: //var sql = await redb.Query() // .Where(x => x.Salary > 50000) // .GroupBy(x => x.Department) // .ToSqlStringAsync(g => new { Dept = g.Key, Count = Agg.Count(g) }); //Console.WriteLine(sql); var byDeptFiltered = await redb.Query() .Where(x => x.Salary > 50000m) .GroupBy(x => x.Department) .SelectAsync(g => new { Department = g.Key, TotalSalary = Agg.Sum(g, x => x.Salary), MaxFloor = Agg.Max(g, x => x.HomeAddress!.Building!.Floor), Count = Agg.Count(g) }); sw.Stop(); var first = byDeptFiltered.FirstOrDefault(); return Ok("E129", "GroupBy - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, byDeptFiltered.Count, [$"Filter: Salary > 50k", $"Groups: {byDeptFiltered.Count}, First: {first?.Department ?? "N/A"}, Max home floor: {first?.MaxFloor}"]); } } Path: redb/redb.Examples/Examples/E130_GroupByListItem.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E130_GroupByListItem.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// GroupBy by a ListItem-typed property. /// Probes 3 flavors: /// (1) GroupBy(p => p.Status!.Id) - key as long /// (2) GroupBy(p => p.Status!.Value) - key as string /// (3) GroupBy(p => p.Status) - the bare ListItem class as key /// Pro/OSS parity check for grouping over RedbListItem fields. /// Requires E114-E118 to run first. /// [ExampleMeta("E130", "GroupBy - by ListItem (Id/Value/Bare)", "Analytics", ExampleTier.Free, 130, "GroupBy", "ListItem", "Aggregation", "Analytics", RelatedApis = ["IRedbQueryable.GroupBy", "RedbListItem"])] public class E130_GroupByListItem : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var notes = new List(); // (1) GroupBy by Status.Id (long key) try { var q1 = redb.Query().GroupBy(p => p.Status!.Id); // var sql1 = await q1.ToSqlStringAsync(g => new // { // StatusId = g.Key, // Count = Agg.Count(g), // AvgAge = Agg.Average(g, x => x.Age) // }); // Console.WriteLine("[E130-SQL-1]\n" + sql1); var byId = await q1.SelectAsync(g => new { StatusId = g.Key, Count = Agg.Count(g), AvgAge = Agg.Average(g, x => x.Age) }); notes.Add($"(1) by Status.Id: groups={byId.Count}; first=Id:{byId.FirstOrDefault()?.StatusId}, cnt={byId.FirstOrDefault()?.Count}"); } catch (Exception ex) { notes.Add($"(1) by Status.Id: FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}"); Console.WriteLine("[E130-1] " + ex); } // (2) GroupBy by Status.Value (string key) try { var q2 = redb.Query().GroupBy(p => p.Status!.Value); // var sql2 = await q2.ToSqlStringAsync(g => new // { // StatusValue = g.Key, // Count = Agg.Count(g) // }); // Console.WriteLine("[E130-SQL-2]\n" + sql2); var byValue = await q2.SelectAsync(g => new { StatusValue = g.Key, Count = Agg.Count(g) }); notes.Add($"(2) by Status.Value: groups={byValue.Count}; first=\"{byValue.FirstOrDefault()?.StatusValue}\", cnt={byValue.FirstOrDefault()?.Count}"); } catch (Exception ex) { notes.Add($"(2) by Status.Value: FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}"); Console.WriteLine("[E130-2] " + ex); } // (3) GroupBy by bare Status (RedbListItem class itself) try { var q3 = redb.Query().GroupBy(p => p.Status); // var sql3 = await q3.ToSqlStringAsync(g => new // { // Status = g.Key, // Count = Agg.Count(g) // }); // Console.WriteLine("[E130-SQL-3]\n" + sql3); var byBare = await q3.SelectAsync(g => new { Status = g.Key, Count = Agg.Count(g) }); var first = byBare.FirstOrDefault(); var firstDesc = first?.Status is RedbListItem li ? $"Id:{li.Id}, Value:'{li.Value}'" : (first?.Status is null ? "null" : first.Status.ToString()); notes.Add($"(3) by bare Status: groups={byBare.Count}; first={firstDesc}, cnt={first?.Count}"); } catch (Exception ex) { notes.Add($"(3) by bare Status: FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}"); Console.WriteLine("[E130-3] " + ex); } sw.Stop(); foreach (var n in notes) Console.WriteLine("[E130-NOTE] " + n); return Ok("E130", "GroupBy - by ListItem (Id/Value/Bare)", ExampleTier.Free, sw.ElapsedMilliseconds, notes.Count, notes.ToArray()); } } Path: redb/redb.Examples/Examples/E130_GroupByMultiKey.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E130_GroupByMultiKey.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// GroupBy with composite key (multiple fields). /// Group by Department AND Position for detailed breakdown; one aggregate reads a field two nested /// classes deep (HomeAddress.Building.Floor). /// [ExampleMeta("E130a", "GroupBy - Composite Key", "Analytics", ExampleTier.Free, 130, "GroupBy", "Composite", "MultiKey", "Analytics", RelatedApis = ["IRedbQueryable.GroupBy"])] public class E130_GroupByMultiKey : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Uncomment to see generated SQL: // var sql = await redb.Query() // .GroupBy(x => new { x.Department, x.Position }) // .ToSqlStringAsync(g => new { g.Key.Department, g.Key.Position, Count = Agg.Count(g) }); // Console.WriteLine(sql); var byDeptPosition = await redb.Query() .GroupBy(x => new { x.Department, x.Position }) .SelectAsync(g => new { g.Key.Department, g.Key.Position, TotalSalary = Agg.Sum(g, x => x.Salary), AvgFloor = Agg.Average(g, x => x.HomeAddress!.Building!.Floor), Count = Agg.Count(g) }); sw.Stop(); var first = byDeptPosition.FirstOrDefault(); return Ok("E130a", "GroupBy - Composite Key", ExampleTier.Free, sw.ElapsedMilliseconds, byDeptPosition.Count, [$"Groups: {byDeptPosition.Count}", $"First: {first?.Department ?? "N/A"}/{first?.Position ?? "N/A"}, Avg home floor: {first?.AvgFloor:F2}"]); } } Path: redb/redb.Examples/Examples/E131_GroupByRedb.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E131_GroupByRedb.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// GroupBy on base RedbObject fields without JOIN. /// Groups by SchemeId or OwnerId directly from _objects table. /// Much faster than GroupBy on Props fields. /// [ExampleMeta("E131", "GroupByRedb - Base Fields", "Analytics", ExampleTier.Free, 131, "GroupByRedb", "Base", "NoJoin", "Analytics", RelatedApis = ["IRedbQueryable.GroupByRedb"])] public class E131_GroupByRedb : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Uncomment to see generated SQL: // var sql = await redb.Query() // .GroupByRedb(x => x.OwnerId) // .ToSqlStringAsync(g => new { Owner = g.Key, Count = Agg.Count(g) }); // Console.WriteLine(sql); // GroupBy on base field (no JOIN with _values!) var byOwner = await redb.Query() .GroupByRedb(x => x.OwnerId) .SelectAsync(g => new { OwnerId = g.Key, TotalSalary = Agg.Sum(g, x => x.Salary), AvgFloor = Agg.Average(g, x => x.HomeAddress!.Building!.Floor), Count = Agg.Count(g) }); sw.Stop(); var first = byOwner.FirstOrDefault(); return Ok("E131", "GroupByRedb - Base Fields", ExampleTier.Free, sw.ElapsedMilliseconds, byOwner.Count, [$"SQL: GROUP BY o._id_owner (NO JOIN!)", $"Groups: {byOwner.Count}, First owner: {first?.OwnerId ?? 0}", $"Avg home floor of the first owner: {first?.AvgFloor:F2}"]); } } Path: redb/redb.Examples/Examples/E132_WindowRowNumber.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E132_WindowRowNumber.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window function ROW_NUMBER() with PARTITION BY. /// Ranks employees within each department by salary. /// [ExampleMeta("E132", "Window - RowNumber", "Analytics", ExampleTier.Free, 132, "Window", "RowNumber", "Rank", "Partition", RelatedApis = ["IRedbQueryable.WithWindow", "Win.RowNumber"])] public class E132_WindowRowNumber : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var windowQuery = redb.Query() .Take(50) .WithWindow(w => w .PartitionBy(x => x.Department) .OrderByDesc(x => x.Salary)); // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(x => new { x.Name, Rank = Win.RowNumber() }); // Console.WriteLine(sql); var ranked = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Department = x.Props.Department, Salary = x.Props.Salary, Rank = Win.RowNumber() }); sw.Stop(); var top = ranked.FirstOrDefault(); return Ok("E132", "Window - RowNumber", ExampleTier.Free, sw.ElapsedMilliseconds, ranked.Count, [$"ROW_NUMBER() PARTITION BY Department", $"#1 in {top?.Department ?? "N/A"}: {top?.Name ?? "N/A"}"]); } } Path: redb/redb.Examples/Examples/E133_WindowRunningSum.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E133_WindowRunningSum.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window function SUM() OVER for running totals. /// Calculates cumulative salary within each department. /// [ExampleMeta("E133", "Window - Running Sum", "Analytics", ExampleTier.Free, 133, "Window", "Sum", "Running", "Cumulative", RelatedApis = ["IRedbQueryable.WithWindow", "Win.Sum"])] public class E133_WindowRunningSum : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var windowQuery = redb.Query() .Take(50) .WithWindow(w => w .PartitionBy(x => x.Department) .OrderBy(x => x.HireDate)); // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(x => new { x.Props.Salary, Total = Win.Sum(x.Props.Salary) }); // Console.WriteLine(sql); var running = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Department = x.Props.Department, Salary = x.Props.Salary, RunningTotal = Win.Sum(x.Props.Salary) }); sw.Stop(); var sample = running.FirstOrDefault(); return Ok("E133", "Window - Running Sum", ExampleTier.Free, sw.ElapsedMilliseconds, running.Count, [$"SUM(Salary) OVER (PARTITION BY Dept ORDER BY HireDate)", $"Sample: {sample?.Name ?? "N/A"}, Running: {sample?.RunningTotal ?? 0:N0}"]); } } Path: redb/redb.Examples/Examples/E134_WindowLagLead.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E134_WindowLagLead.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window functions LAG/LEAD for previous/next values. /// Access previous and next employee salary in sequence. /// [ExampleMeta("E134", "Window - Lag/Lead", "Analytics", ExampleTier.Free, 134, "Window", "Lag", "Lead", "Previous", "Next", RelatedApis = ["Win.Lag", "Win.Lead"])] public class E134_WindowLagLead : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var windowQuery = redb.Query() .Take(50) .WithWindow(w => w .PartitionBy(x => x.Department) .OrderBy(x => x.Salary)); // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(x => new { Prev = Win.Lag(x.Props.Salary), Next = Win.Lead(x.Props.Salary) }); // Console.WriteLine(sql); var withLagLead = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Salary = x.Props.Salary, PrevSalary = Win.Lag(x.Props.Salary), NextSalary = Win.Lead(x.Props.Salary) }); sw.Stop(); var sample = withLagLead.Skip(1).FirstOrDefault(); // Skip first (no prev) return Ok("E134", "Window - Lag/Lead", ExampleTier.Free, sw.ElapsedMilliseconds, withLagLead.Count, [$"LAG(Salary), LEAD(Salary)", $"Sample: {sample?.Salary:N0} (prev: {sample?.PrevSalary:N0}, next: {sample?.NextSalary:N0})"]); } } Path: redb/redb.Examples/Examples/E135_WindowRank.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E135_WindowRank.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window functions RANK/DENSE_RANK for ranking with ties. /// RANK skips numbers after ties, DENSE_RANK does not. /// [ExampleMeta("E135", "Window - Rank/DenseRank", "Analytics", ExampleTier.Free, 135, "Window", "Rank", "DenseRank", "Ranking", RelatedApis = ["Win.Rank", "Win.DenseRank"])] public class E135_WindowRank : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var windowQuery = redb.Query() .Take(50) .WithWindow(w => w .PartitionBy(x => x.Department) .OrderByDesc(x => x.Salary)); // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(x => new { Rank = Win.Rank(), Dense = Win.DenseRank() }); // Console.WriteLine(sql); var ranked = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Department = x.Props.Department, Salary = x.Props.Salary, Rank = Win.Rank(), DenseRank = Win.DenseRank() }); sw.Stop(); var sample = ranked.FirstOrDefault(); return Ok("E135", "Window - Rank/DenseRank", ExampleTier.Free, sw.ElapsedMilliseconds, ranked.Count, [$"RANK() vs DENSE_RANK() by Salary", $"Top: {sample?.Name ?? "N/A"}, Rank: {sample?.Rank}, Dense: {sample?.DenseRank}"]); } } Path: redb/redb.Examples/Examples/E136_WindowNtile.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E136_WindowNtile.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window function NTILE for bucket distribution. /// Divides employees into N equal groups (quartiles, deciles, etc.). /// [ExampleMeta("E136", "Window - Ntile", "Analytics", ExampleTier.Free, 136, "Window", "Ntile", "Quartile", "Bucket", RelatedApis = ["Win.Ntile"])] public class E136_WindowNtile : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var windowQuery = redb.Query() .Take(100) .WithWindow(w => w.OrderByDesc(x => x.Salary)); // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(x => new { Quartile = Win.Ntile(4) }); // Console.WriteLine(sql); // Divide into 4 quartiles by salary var quartiles = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Salary = x.Props.Salary, Quartile = Win.Ntile(4) }); sw.Stop(); var q1Count = quartiles.Count(x => x.Quartile == 1); var topEarner = quartiles.FirstOrDefault(); return Ok("E136", "Window - Ntile", ExampleTier.Free, sw.ElapsedMilliseconds, quartiles.Count, [$"NTILE(4) - split into quartiles", $"Q1 (top 25%): {q1Count} employees"]); } } Path: redb/redb.Examples/Examples/E137_WindowFirstLast.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E137_WindowFirstLast.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window functions FIRST_VALUE/LAST_VALUE. /// Get first and last salary in partition for comparison. /// [ExampleMeta("E137", "Window - FirstValue/LastValue", "Analytics", ExampleTier.Free, 137, "Window", "FirstValue", "LastValue", RelatedApis = ["Win.FirstValue", "Win.LastValue"])] public class E137_WindowFirstLast : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var windowQuery = redb.Query() .Take(50) .WithWindow(w => w .PartitionBy(x => x.Department) .OrderByDesc(x => x.Salary)); // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(x => new { Max = Win.FirstValue(x.Props.Salary), Min = Win.LastValue(x.Props.Salary) }); // Console.WriteLine(sql); var withMinMax = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Department = x.Props.Department, Salary = x.Props.Salary, MaxInDept = Win.FirstValue(x.Props.Salary), // First = highest (DESC order) MinInDept = Win.LastValue(x.Props.Salary) // Last = lowest }); sw.Stop(); var sample = withMinMax.FirstOrDefault(); return Ok("E137", "Window - FirstValue/LastValue", ExampleTier.Free, sw.ElapsedMilliseconds, withMinMax.Count, [$"FIRST_VALUE/LAST_VALUE in partition", $"{sample?.Department ?? "N/A"}: max={sample?.MaxInDept:N0}, min={sample?.MinInDept:N0}"]); } } Path: redb/redb.Examples/Examples/E138_WindowFrame.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E138_WindowFrame.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window function with custom frame (sliding window). /// Calculate moving average over last N rows. /// [ExampleMeta("E138", "Window - Frame (Sliding)", "Analytics", ExampleTier.Free, 138, "Window", "Frame", "Sliding", "Moving", RelatedApis = ["WindowBuilder.Frame", "Frame.Rows"])] public class E138_WindowFrame : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var windowQuery = redb.Query() .Take(50) .WithWindow(w => w .PartitionBy(x => x.Department) .OrderBy(x => x.HireDate) .Frame(Frame.Rows(3))); // ROWS BETWEEN 3 PRECEDING AND CURRENT ROW // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(x => new { MovingSum = Win.Sum(x.Props.Salary) }); // Console.WriteLine(sql); var movingAvg = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Salary = x.Props.Salary, MovingSum = Win.Sum(x.Props.Salary) // Sum of last 4 rows (3 + current) }); sw.Stop(); var sample = movingAvg.Skip(3).FirstOrDefault(); // Skip first 3 (partial windows) return Ok("E138", "Window - Frame (Sliding)", ExampleTier.Free, sw.ElapsedMilliseconds, movingAvg.Count, [$"ROWS BETWEEN 3 PRECEDING AND CURRENT", $"Moving sum (4 rows): {sample?.MovingSum:N0}"]); } } Path: redb/redb.Examples/Examples/E139_DistinctRedb.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E139_DistinctRedb.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// DISTINCT ON base fields (without Id) for finding duplicates. /// Finds objects with identical Name, CodeInt etc. (potential duplicates). /// [ExampleMeta("E139", "DistinctRedb - Find Duplicates", "Analytics", ExampleTier.Pro, 139, "Distinct", "DistinctRedb", "Duplicates", RelatedApis = ["IRedbQueryable.DistinctRedb"])] public class E139_DistinctRedb : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .OrderByRedb(o => o.Id) .DistinctRedb() .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var unique = await query.ToListAsync(); sw.Stop(); return Ok("E139", "DistinctRedb - Find Duplicates", ExampleTier.Pro, sw.ElapsedMilliseconds, unique.Count, [$"DISTINCT ON (base fields except _id)", $"Unique: {unique.Count} objects"]); } } Path: redb/redb.Examples/Examples/E140_DistinctByRedb.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E140_DistinctByRedb.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// DISTINCT ON specific base field. /// Get one object per unique Name (first by Id). /// [ExampleMeta("E140", "DistinctByRedb - By Field", "Analytics", ExampleTier.Pro, 140, "Distinct", "DistinctByRedb", "Unique", RelatedApis = ["IRedbQueryable.DistinctByRedb"])] public class E140_DistinctByRedb : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .DistinctByRedb(x => x.Name) .Take(100); // Uncomment to see generated SQL: //var sql = await query.ToSqlStringAsync(); //Console.WriteLine(sql); var uniqueByName = await query.ToListAsync(); sw.Stop(); var names = string.Join(", ", uniqueByName.Take(3).Select(x => x.name)); return Ok("E140", "DistinctByRedb - By Field", ExampleTier.Pro, sw.ElapsedMilliseconds, uniqueByName.Count, [$"DISTINCT ON (o._name)", $"First 3: {names}..."]); } } Path: redb/redb.Examples/Examples/E141_WhereInRedb.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E141_WhereInRedb.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter by list of base field values. /// WHERE o._id IN (...) without JOIN - very fast. /// [ExampleMeta("E141", "WhereInRedb - Base Field", "Analytics", ExampleTier.Free, 141, "WhereIn", "WhereInRedb", "Base", "Filter", RelatedApis = ["IRedbQueryable.WhereInRedb"])] public class E141_WhereInRedb : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // First get some IDs to filter by var sampleIds = await redb.Query() .Take(5) .Select(x => x.id) .ToListAsync(); if (sampleIds.Count == 0) { sw.Stop(); return Fail("E141", "WhereInRedb - Base Field", ExampleTier.Free, sw.ElapsedMilliseconds, "No employees found. Run E000 first."); } var query = redb.Query() .WhereInRedb(x => x.Id, sampleIds); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); return Ok("E141", "WhereInRedb - Base Field", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"WHERE o._id IN ({string.Join(",", sampleIds.Take(3))}...)", $"Found: {results.Count} (NO JOIN!)"]); } } Path: redb/redb.Examples/Examples/E142_GroupByArray.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E142_GroupByArray.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Groups objects by the elements of an array nested two levels deep using GroupByArray. /// Path: EmployeeProps -> Contacts[] -> Contact.Metadata[] -> ContactDetail.Label, flattened with SelectMany. /// The owner filter reads two nested classes (HomeAddress.Building.Floor), each group carries a total and a /// conditional count, a window ranks the groups, and ToSqlStringAsync shows the statement that runs. /// [ExampleMeta("E142", "GroupByArray - Nested Array Elements", "Analytics", ExampleTier.Free, 142, "GroupByArray", "Array", "Expand", "SelectMany", "Window", "Rank", RelatedApis = ["IRedbQueryable.GroupByArray", "IRedbGroupedQueryable.WithWindow", "Agg.Count"])] public class E142_GroupByArray : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Employees living above the 10th floor; the metadata entries of all their contacts are grouped by label. var byLabel = redb.Query() .Where(e => e.Contacts != null && e.HomeAddress!.Building!.Floor > 10) .GroupByArray(e => e.Contacts!.SelectMany(c => c.Metadata!), m => m.Label) .WithWindow(w => w.OrderByDesc(g => Agg.Count(g))); var ranked = await byLabel.SelectAsync(g => new { Label = g.Key, Entries = Agg.Count(g), CorporateDomain = Agg.Count(g, m => m.Value == "company.com"), Rank = Win.Rank() }); sw.Stop(); var sql = await byLabel.ToSqlStringAsync(g => new { Label = g.Key, Entries = Agg.Count(g), CorporateDomain = Agg.Count(g, m => m.Value == "company.com"), Rank = Win.Rank() }); var output = ranked.OrderBy(g => g.Rank).ThenBy(g => g.Label) .Select(g => $"#{g.Rank} {g.Label}: {g.Entries} entries, {g.CorporateDomain} with value company.com") .Prepend($"Groups by Contacts[].Metadata[].Label, home floor > 10: {ranked.Count}") .Append("SQL:") .Concat(sql.Split('\n').Select(l => l.TrimEnd('\r'))) .ToArray(); return Ok("E142", "GroupByArray - Nested Array Elements", ExampleTier.Free, sw.ElapsedMilliseconds, ranked.Count, output); } } Path: redb/redb.Examples/Examples/E143_SumRedbAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E143_SumRedbAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// SumRedbAsync - sum of base IRedbObject field WITHOUT JOIN to _values. /// Much faster than SumAsync for base fields like Id. /// [ExampleMeta("E143", "SumRedbAsync - Base Field Sum", "Analytics", ExampleTier.Free, 143, "SumRedbAsync", "Aggregation", "NoJoin", RelatedApis = ["IRedbQueryable.SumRedbAsync"])] public class E143_SumRedbAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Sum of base field Id (from _objects table, NO JOIN with _values!) var sumId = await redb.Query().SumRedbAsync(x => x.Id); // Compare with regular count var count = await redb.Query().CountAsync(); sw.Stop(); return Ok("E143", "SumRedbAsync - Base Field Sum", ExampleTier.Free, sw.ElapsedMilliseconds, count, [$"SUM(o._id) = {sumId:N0}", $"NO JOIN with _values!", $"Count: {count}"]); } } Path: redb/redb.Examples/Examples/E144_MinMaxRedbAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E144_MinMaxRedbAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// MinRedbAsync/MaxRedbAsync - min/max of base IRedbObject fields WITHOUT JOIN. /// Perfect for finding date ranges (DateCreate, DateModify). /// [ExampleMeta("E144", "Min/MaxRedbAsync - Date Range", "Analytics", ExampleTier.Free, 144, "MinRedbAsync", "MaxRedbAsync", "DateRange", RelatedApis = ["IRedbQueryable.MinRedbAsync", "IRedbQueryable.MaxRedbAsync"])] public class E144_MinMaxRedbAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Min/Max of DateCreate (from _objects table, NO JOIN!) var minDate = await redb.Query().MinRedbAsync(x => x.DateCreate); var maxDate = await redb.Query().MaxRedbAsync(x => x.DateCreate); sw.Stop(); var range = minDate.HasValue && maxDate.HasValue ? (maxDate.Value - minDate.Value).Days : 0; return Ok("E144", "Min/MaxRedbAsync - Date Range", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [$"First: {minDate?.ToString("yyyy-MM-dd") ?? "N/A"}", $"Last: {maxDate?.ToString("yyyy-MM-dd") ?? "N/A"}", $"Range: {range} days (NO JOIN!)"]); } } Path: redb/redb.Examples/Examples/E145_AverageRedbAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E145_AverageRedbAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// AverageRedbAsync - average of base IRedbObject field WITHOUT JOIN. /// Useful for statistics on Id distribution. /// [ExampleMeta("E145", "AverageRedbAsync - Base Field Avg", "Analytics", ExampleTier.Free, 145, "AverageRedbAsync", "Aggregation", "NoJoin", RelatedApis = ["IRedbQueryable.AverageRedbAsync"])] public class E145_AverageRedbAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Average of base field Id (from _objects table, NO JOIN!) var avgId = await redb.Query().AverageRedbAsync(x => x.Id); // Get min/max for context var minId = await redb.Query().MinRedbAsync(x => x.Id); var maxId = await redb.Query().MaxRedbAsync(x => x.Id); sw.Stop(); return Ok("E145", "AverageRedbAsync - Base Field Avg", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"AVG(o._id) = {avgId:F2}", $"Range: {minId?.ToString() ?? "N/A"} - {maxId?.ToString() ?? "N/A"}", "NO JOIN with _values!"]); } } Path: redb/redb.Examples/Examples/E146_AggregateRedbAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E146_AggregateRedbAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// AggregateRedbAsync - batch aggregation of base IRedbObject fields in ONE query. /// Combines Sum, Min, Max, Avg, Count on base fields WITHOUT JOIN. /// [ExampleMeta("E146", "AggregateRedbAsync - Batch Base", "Analytics", ExampleTier.Free, 146, "AggregateRedbAsync", "Batch", "NoJoin", RelatedApis = ["IRedbQueryable.AggregateRedbAsync", "Agg.Sum", "Agg.Min", "Agg.Max"])] public class E146_AggregateRedbAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Multiple aggregations on base fields in ONE query (NO JOIN!) var stats = await redb.Query() .AggregateRedbAsync(x => new { MaxId = Agg.Max(x.Id), MinDateCreate = Agg.Min(x.DateCreate), MaxDateModify = Agg.Max(x.DateModify), AvgId = Agg.Average(x.Id), Count = Agg.Count() }); sw.Stop(); return Ok("E146", "AggregateRedbAsync - Batch Base", ExampleTier.Free, sw.ElapsedMilliseconds, (int)stats.Count, [$"5 aggregations in 1 query (NO JOIN!)", $"MaxId: {stats.MaxId}, Count: {stats.Count}", $"Dates: {stats.MinDateCreate:yyyy-MM-dd} - {stats.MaxDateModify:yyyy-MM-dd}"]); } } Path: redb/redb.Examples/Examples/E147_WindowPartitionByRedb.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E147_WindowPartitionByRedb.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// PartitionByRedb in Window Functions - partition by base IRedbObject field. /// SQL: PARTITION BY o._id_scheme (NO JOIN for partition key!) /// [ExampleMeta("E147", "Window - PartitionByRedb", "Analytics", ExampleTier.Free, 147, "PartitionByRedb", "Window", "NoJoin", RelatedApis = ["IWindowBuilder.PartitionByRedb", "Win.RowNumber"])] public class E147_WindowPartitionByRedb : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Window with PartitionByRedb (base field) + OrderByDesc (Props field) var ranked = await redb.Query() .Take(50) .WithWindow(w => w .PartitionByRedb(x => x.SchemeId) // Base field - NO JOIN! .OrderByDesc(x => x.Salary)) // Props field .SelectAsync(x => new { x.Name, SchemeId = x.SchemeId, Salary = x.Props.Salary, RankInScheme = Win.RowNumber() }); sw.Stop(); var first = ranked.FirstOrDefault(); return Ok("E147", "Window - PartitionByRedb", ExampleTier.Free, sw.ElapsedMilliseconds, ranked.Count, [$"PARTITION BY o._id_scheme (NO JOIN!)", $"Ranked: {ranked.Count} employees", first != null ? $"Top: #{first.RankInScheme} {first.Name} ${first.Salary:N0}" : "No data"]); } } Path: redb/redb.Examples/Examples/E148_WindowOrderByRedb.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E148_WindowOrderByRedb.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// OrderByRedb in Window Functions - order by base IRedbObject field. /// SQL: ORDER BY o._date_create (NO JOIN for order key!) /// [ExampleMeta("E148", "Window - OrderByRedb", "Analytics", ExampleTier.Free, 148, "OrderByRedb", "Window", "NoJoin", RelatedApis = ["IWindowBuilder.OrderByRedb", "Win.Count", "Frame.Rows"])] public class E148_WindowOrderByRedb : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Window with OrderByRedb (base field) + Frame var ordered = await redb.Query() .Take(50) .WithWindow(w => w .OrderByRedb(x => x.DateCreate) // Base field - NO JOIN! .Frame(Frame.Rows().UnboundedPreceding())) .SelectAsync(x => new { x.Name, Created = x.DateCreate, Salary = x.Props.Salary, RunningCount = Win.Count() }); sw.Stop(); var last = ordered.LastOrDefault(); return Ok("E148", "Window - OrderByRedb", ExampleTier.Free, sw.ElapsedMilliseconds, ordered.Count, [$"ORDER BY o._date_create (NO JOIN!)", $"Employees: {ordered.Count}", last != null ? $"Last: {last.Name} #{last.RunningCount}" : "No data"]); } } Path: redb/redb.Examples/Examples/E149_SelectProjection.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E149_SelectProjection.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Select projection - load only specific fields instead of full object. /// Reduces data transfer and improves performance. /// [ExampleMeta("E149", "Select - Projection", "Query", ExampleTier.Free, 149, "Select", "Projection", "Performance", RelatedApis = ["IRedbQueryable.Select"])] public class E149_SelectProjection : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Project only 3 fields from 20+ available var projected = await redb.Query() .Take(100) .Select(x => new { x.id, x.Props.FirstName, x.Props.Salary, HomeCity = x.Props.HomeAddress!.City, HomeFloor = x.Props.HomeAddress!.Building!.Floor }) .ToListAsync(); // Compare with full load var swFull = Stopwatch.StartNew(); var full = await redb.Query().Take(100).ToListAsync(); swFull.Stop(); sw.Stop(); var first = projected.FirstOrDefault(); return Ok("E149", "Select - Projection", ExampleTier.Free, sw.ElapsedMilliseconds, projected.Count, [$"Projected 5 fields, 2 of them nested: {sw.ElapsedMilliseconds}ms", $"Full load 20+ fields: {swFull.ElapsedMilliseconds}ms", first != null ? $"First: {first.FirstName} ${first.Salary:N0}, home {first.HomeCity}, floor {first.HomeFloor}" : "No data"]); } } Path: redb/redb.Examples/Examples/E150A_ArrayAggregationByIndex.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E150A_ArrayAggregationByIndex.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Array aggregation - aggregate one element of an array field by its index. /// SkillLevels[0] is the level of the first skill of each employee. /// For all elements see E150. /// [ExampleMeta("E150A", "Array Aggregation - By Index", "Analytics", ExampleTier.Free, 150, "Array", "Aggregation", "Index", RelatedApis = ["Agg.Sum", "Agg.Average"])] public class E150A_ArrayAggregationByIndex : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Aggregate specific index: SkillLevels[0] (first skill) var firstElement = await redb.Query() .AggregateAsync(x => new { SumFirstSkill = Agg.Sum(x.Props.SkillLevels[0]), AvgFirstSkill = Agg.Average(x.Props.SkillLevels[0]) }); sw.Stop(); return Ok("E150A", "Array Aggregation - By Index", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"SkillLevels[0]: Sum={firstElement.SumFirstSkill}, Avg={firstElement.AvgFirstSkill:F2}"]); } } Path: redb/redb.Examples/Examples/E150_ArrayAggregation.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E150_ArrayAggregation.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Array aggregation - aggregate all elements of an array field. /// SkillLevels[] contains numeric values (1-5) for aggregation. /// For one element by its index see E150A. /// [ExampleMeta("E150", "Array Aggregation - All Elements", "Analytics", ExampleTier.Free, 150, "Array", "Aggregation", "Sum", RelatedApis = ["Agg.Sum", "Agg.Average"])] public class E150_ArrayAggregation : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Aggregate ALL elements of SkillLevels[] array var allElements = await redb.Query() .AggregateAsync(x => new { TotalSkillPoints = Agg.Sum(x.Props.SkillLevels.Select(s => s)), AvgSkillLevel = Agg.Average(x.Props.SkillLevels.Select(s => s)), Count = Agg.Count() }); sw.Stop(); return Ok("E150", "Array Aggregation - All Elements", ExampleTier.Free, sw.ElapsedMilliseconds, (int)allElements.Count, [$"All SkillLevels[]: Sum={allElements.TotalSkillPoints}, Avg={allElements.AvgSkillLevel:F2}", $"Employees: {allElements.Count}"]); } } Path: redb/redb.Examples/Examples/E151_ArithmeticMultiply.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E151_ArithmeticMultiply.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates arithmetic multiplication in Where clause. /// Calculates annual salary (monthly * 12) and filters employees earning over 1M per year. /// Pro feature: server-side arithmetic expressions. /// [ExampleMeta("E151", "Where - Arithmetic Multiply", "Query", ExampleTier.Pro, 151, "Arithmetic", "Multiply", "Expression", RelatedApis = ["IRedbQueryable.Where"])] public class E151_ArithmeticMultiply : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees with annual salary > 1,000,000 // Server-side: Salary * 12 > 1000000 var query = redb.Query() .Where(e => e.Salary * 12 > 1_000_000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var highEarners = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.Salary * 12 > 1_000_000m) .CountAsync(); sw.Stop(); var first = highEarners.FirstOrDefault(); var annualSalary = first?.Props.Salary * 12 ?? 0; return Ok("E151", "Where - Arithmetic Multiply", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: Salary * 12 > 1,000,000", $"Found: {totalCount} high earners", $"First: {first?.Props.FirstName} {first?.Props.LastName}, Annual: ${annualSalary:N0}"]); } } Path: redb/redb.Examples/Examples/E152_ArithmeticAddFields.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E152_ArithmeticAddFields.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates arithmetic operations combining multiple fields in Where clause. /// Creates a "scoring" formula using Age and Salary to find senior valuable employees. /// Pro feature: server-side arithmetic with multiple Props fields. /// [ExampleMeta("E152", "Where - Arithmetic Add Fields", "Query", ExampleTier.Pro, 152, "Arithmetic", "Add", "MultiField", RelatedApis = ["IRedbQueryable.Where"])] public class E152_ArithmeticAddFields : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Combined scoring: Age * 1000 + Salary > 120000 // Example: Age 40, Salary 85000 -> 40*1000 + 85000 = 125000 > 120000 var query = redb.Query() .Where(e => e.Age * 1000 + e.Salary > 120_000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.Age * 1000 + e.Salary > 120_000m) .CountAsync(); sw.Stop(); var first = results.FirstOrDefault(); var score = first != null ? first.Props.Age * 1000 + (int)first.Props.Salary : 0; return Ok("E152", "Where - Arithmetic Add Fields", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Formula: Age * 1000 + Salary > 120,000", $"Found: {totalCount} employees", $"First: {first?.Props.FirstName}, Age {first?.Props.Age}, Score: {score:N0}"]); } } Path: redb/redb.Examples/Examples/E153_StringToLower.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E153_StringToLower.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates case-insensitive string search using ToLower() in Where clause. /// Finds employees whose last name contains "s" regardless of case (Smith, Jones, etc.). /// Pro feature: server-side LOWER() function. /// [ExampleMeta("E153", "Where - String ToLower", "Query", ExampleTier.Pro, 153, "String", "ToLower", "CaseInsensitive", RelatedApis = ["IRedbQueryable.Where", "String.ToLower"])] public class E153_StringToLower : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Case-insensitive search: LastName contains "s" (Smith, Jones, Anderson, etc.) var query = redb.Query() .Where(e => e.LastName.ToLower().Contains("s")) .Take(100); // Uncomment to see generated SQL (contains LOWER): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.LastName.ToLower().Contains("s")) .CountAsync(); sw.Stop(); var names = results.Take(3).Select(e => e.Props.LastName); return Ok("E153", "Where - String ToLower", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: LastName.ToLower().Contains(\"s\")", $"Found: {totalCount} employees", $"Examples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/Examples/E154_StringTrim.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E154_StringTrim.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates Trim() function in Where clause to filter out empty or whitespace-only values. /// Finds employees with meaningful first names (not empty after trimming). /// Pro feature: server-side TRIM() function. /// [ExampleMeta("E154", "Where - String Trim", "Query", ExampleTier.Pro, 154, "String", "Trim", "Validation", RelatedApis = ["IRedbQueryable.Where", "String.Trim"])] public class E154_StringTrim : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees with non-empty trimmed first names longer than 3 chars var query = redb.Query() .Where(e => e.FirstName.Trim().Length > 3) .Take(100); // Uncomment to see generated SQL (contains TRIM): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.FirstName.Trim().Length > 3) .CountAsync(); sw.Stop(); var names = results.Take(5).Select(e => $"{e.Props.FirstName} ({e.Props.FirstName.Length} chars)"); return Ok("E154", "Where - String Trim", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: FirstName.Trim().Length > 3", $"Found: {totalCount} employees", $"Examples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/Examples/E155_StringChain.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E155_StringChain.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates chaining multiple string functions in Where clause. /// Finds employees in departments with long uppercase names. /// Pro feature: server-side chained UPPER() + LENGTH() functions. /// [ExampleMeta("E155", "Where - String Chain", "Query", ExampleTier.Pro, 155, "String", "ToUpper", "Length", "Chain", RelatedApis = ["IRedbQueryable.Where", "String.ToUpper", "String.Length"])] public class E155_StringChain : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees in departments with names longer than 5 characters var query = redb.Query() .Where(e => e.Department.ToUpper().Length > 5) .Take(100); // Uncomment to see generated SQL (contains UPPER + LENGTH): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.Department.ToUpper().Length > 5) .CountAsync(); sw.Stop(); var depts = results.Select(e => e.Props.Department).Distinct().Take(5); return Ok("E155", "Where - String Chain", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: Department.ToUpper().Length > 5", $"Found: {totalCount} employees", $"Departments: {string.Join(", ", depts)}"]); } } Path: redb/redb.Examples/Examples/E156_MathAbs.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E156_MathAbs.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates Math.Abs() in Where clause for range filtering around a target value. /// Finds employees aged 30-40 (within 5 years of 35). /// Pro feature: server-side ABS() function. /// [ExampleMeta("E156", "Where - Math.Abs", "Query", ExampleTier.Pro, 156, "Math", "Abs", "Range", RelatedApis = ["IRedbQueryable.Where", "Math.Abs"])] public class E156_MathAbs : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees aged 30-40 (within 5 years of 35) // |Age - 35| <= 5 means Age is between 30 and 40 var query = redb.Query() .Where(e => Math.Abs(e.Age - 35) <= 5) .Take(100); // Uncomment to see generated SQL (contains ABS): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => Math.Abs(e.Age - 35) <= 5) .CountAsync(); sw.Stop(); var ages = results.Take(5).Select(e => e.Props.Age); var avgAge = results.Any() ? results.Average(e => e.Props.Age) : 0; return Ok("E156", "Where - Math.Abs", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: |Age - 35| <= 5 (ages 30-40)", $"Found: {totalCount} employees", $"Ages: {string.Join(", ", ages)}, Avg: {avgAge:F1}"]); } } Path: redb/redb.Examples/Examples/E157_DateTimeYear.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E157_DateTimeYear.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates DateTime property extraction in WhereRedb clause. /// Finds objects created in the current year using DateCreate.Year. /// Pro feature: server-side EXTRACT(YEAR FROM date) function. /// [ExampleMeta("E157", "WhereRedb - DateTime.Year", "Query", ExampleTier.Pro, 157, "DateTime", "Year", "Extract", RelatedApis = ["IRedbQueryable.WhereRedb", "DateTime.Year"])] public class E157_DateTimeYear : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var currentYear = DateTime.UtcNow.Year; Console.WriteLine($"Current Year: {currentYear}$"); // Find employees created in the current year // Uses base field DateCreate (not Props) via WhereRedb var query = redb.Query() .WhereRedb(o => o.DateCreate.Year == currentYear) .Where(e => e.Age > 30) .Take(100); // Uncomment to see generated SQL (contains EXTRACT): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine("Generated SQL:\n" + sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .WhereRedb(o => o.DateCreate.Year == currentYear) .CountAsync(); sw.Stop(); var dates = results.Take(3).Select(e => e.date_create.ToString("yyyy-MM-dd")); return Ok("E157", "WhereRedb - DateTime.Year", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: DateCreate.Year == {currentYear}", $"Found: {totalCount} objects created this year", $"Dates: {string.Join(", ", dates)}"]); } } Path: redb/redb.Examples/Examples/E158_Parentheses.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E158_Parentheses.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates parentheses for operation priority in Where clause. /// Calculates monthly salary (annual / 12) and filters employees earning over $7,000/month. /// Pro feature: server-side arithmetic with correct operator precedence. /// [ExampleMeta("E158", "Where - Parentheses Priority", "Query", ExampleTier.Pro, 158, "Arithmetic", "Parentheses", "Priority", RelatedApis = ["IRedbQueryable.Where"])] public class E158_Parentheses : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees with monthly salary > $7,000 // Parentheses ensure division happens first: (Salary / 12) > 7000 var query = redb.Query() .Where(e => (e.Salary / 12m) > 7000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => (e.Salary / 12m) > 7000m) .CountAsync(); sw.Stop(); var first = results.FirstOrDefault(); var monthly = first?.Props.Salary / 12m ?? 0; return Ok("E158", "Where - Parentheses Priority", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: (Salary / 12) > 7,000 (monthly)", $"Found: {totalCount} employees", $"First: {first?.Props.FirstName}, Monthly: ${monthly:N0}"]); } } Path: redb/redb.Examples/Examples/E159_NestedMath.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E159_NestedMath.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates nested Math functions with arithmetic in Where clause. /// Finds employees with salary close to $80,000 (within $10,000 range). /// Pro feature: server-side ABS() with arithmetic expression inside. /// [ExampleMeta("E159", "Where - Nested Math", "Query", ExampleTier.Pro, 159, "Math", "Nested", "Range", RelatedApis = ["IRedbQueryable.Where", "Math.Abs"])] public class E159_NestedMath : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees with salary in range $70,000 - $90,000 // |Salary - 80000| < 10000 means Salary is between 70k and 90k var query = redb.Query() .Where(e => Math.Abs(e.Salary - 80000m) < 10000m) .Take(100); // Uncomment to see generated SQL (contains ABS with expression): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => Math.Abs(e.Salary - 80000m) < 10000m) .CountAsync(); sw.Stop(); var salaries = results.Take(5).Select(e => $"${e.Props.Salary:N0}"); var avgSalary = results.Any() ? results.Average(e => e.Props.Salary) : 0; return Ok("E159", "Where - Nested Math", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: |Salary - 80k| < 10k ($70k-$90k range)", $"Found: {totalCount} employees", $"Salaries: {string.Join(", ", salaries)}"]); } } Path: redb/redb.Examples/Examples/E160_TreeQueryExpressions.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E160_TreeQueryExpressions.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates arithmetic expressions in TreeQuery Where clause. /// Finds tree nodes where 10% of budget exceeds $50,000. /// Pro feature: server-side arithmetic in tree queries. /// [ExampleMeta("E160", "TreeQuery - Expressions", "Tree", ExampleTier.Pro, 160, "Tree", "Arithmetic", "Expression", RelatedApis = ["IRedbService.TreeQuery", "ITreeQueryable.Where"])] public class E160_TreeQueryExpressions : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E160", "TreeQuery - Expressions", ExampleTier.Pro, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Find departments where 10% of budget > $50,000 (i.e., Budget > $500,000) var query = redb.TreeQuery(root.Id) .Where(d => d.Budget * 0.1m > 50000m) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); var first = results.FirstOrDefault(); var tenPercent = first?.Props.Budget * 0.1m ?? 0; return Ok("E160", "TreeQuery - Expressions", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Budget * 0.1 > 50,000 (Budget > 500k)", $"Found: {results.Count} departments", $"First: {first?.Props.Name}, 10% = ${tenPercent:N0}"]); } } Path: redb/redb.Examples/Examples/E161_SqlFunctionCoalesce.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E161_SqlFunctionCoalesce.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates Sql.Function for calling custom SQL functions. /// Uses COALESCE to safely handle potentially NULL values in comparisons. /// Pro feature: arbitrary SQL function calls via Sql.Function<T>(). /// [ExampleMeta("E161", "Sql.Function - COALESCE", "Query", ExampleTier.Pro, 161, "Sql.Function", "COALESCE", "NULL", RelatedApis = ["Sql.Function"])] public class E161_SqlFunctionCoalesce : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // COALESCE returns first non-NULL argument // Useful for NULL-safe comparisons: COALESCE(Age, 0) > 25 var query = redb.Query() .Where(e => Sql.Function("COALESCE", e.Age, 0) > 30) .Take(100); // Uncomment to see generated SQL (contains COALESCE): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => Sql.Function("COALESCE", e.Age, 0) > 30) .CountAsync(); sw.Stop(); var ages = results.Take(5).Select(e => e.Props.Age); return Ok("E161", "Sql.Function - COALESCE", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"SQL: COALESCE(Age, 0) > 30", $"Found: {totalCount} employees", $"Ages: {string.Join(", ", ages)}"]); } } Path: redb/redb.Examples/Examples/E162_SqlFunctionPower.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E162_SqlFunctionPower.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates Sql.Function for mathematical SQL functions. /// Uses POWER to square the age and filter employees with Age^2 > 900 (Age > 30). /// Pro feature: arbitrary SQL function calls via Sql.Function<T>(). /// [ExampleMeta("E162", "Sql.Function - POWER", "Query", ExampleTier.Pro, 162, "Sql.Function", "POWER", "Math", RelatedApis = ["Sql.Function"])] public class E162_SqlFunctionPower : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // POWER(Age, 2) > 900 means Age^2 > 900, so Age > 30 var query = redb.Query() .Where(e => Sql.Function("POWER", e.Age, 2) > 900) .Take(100); // Uncomment to see generated SQL (contains POWER): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => Sql.Function("POWER", e.Age, 2) > 900) .CountAsync(); sw.Stop(); var ages = results.Take(5).Select(e => $"{e.Props.Age} (^2={e.Props.Age * e.Props.Age})"); return Ok("E162", "Sql.Function - POWER", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"SQL: POWER(Age, 2) > 900 (Age > 30)", $"Found: {totalCount} employees", $"Ages: {string.Join(", ", ages)}"]); } } Path: redb/redb.Examples/Examples/E163_SqlFunctionNested.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E163_SqlFunctionNested.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates nested Sql.Function calls for complex SQL expressions. /// Uses SQRT(Salary) > 250 to find employees with Salary > 62,500. /// Pro feature: nested arbitrary SQL function calls. /// [ExampleMeta("E163", "Sql.Function - Nested", "Query", ExampleTier.Pro, 163, "Sql.Function", "SQRT", "Nested", RelatedApis = ["Sql.Function"])] public class E163_SqlFunctionNested : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // SQRT(Salary) > 250 means Salary > 62,500 var query = redb.Query() .Where(e => Sql.Function("SQRT", e.Salary) > 250) .Take(100); // Uncomment to see generated SQL (contains SQRT): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => Sql.Function("SQRT", e.Salary) > 250) .CountAsync(); sw.Stop(); var salaries = results.Take(5).Select(e => $"${e.Props.Salary:N0} (√={Math.Sqrt((double)e.Props.Salary):F0})"); return Ok("E163", "Sql.Function - Nested", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"SQL: SQRT(Salary) > 250 (Salary > 62,500)", $"Found: {totalCount} employees", $"Salaries: {string.Join(", ", salaries)}"]); } } Path: redb/redb.Examples/Examples/E164_BaseFieldsSingle.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E164_BaseFieldsSingle.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates using RedbObject base fields without Props (no props rows). /// Base fields are stored directly in _objects table for fast access: /// value_string, value_long, value_bool, value_double, value_datetime, value_guid, value_numeric, value_bytes. /// Useful for simple objects, lookups, metadata without dynamic properties. /// [ExampleMeta("E164", "Base Fields - Single Object", "Core", ExampleTier.Free, 164, "BaseFields", "RedbObject", "NoProps", RelatedApis = ["RedbObject", "IRedbService.SaveAsync"])] public class E164_BaseFieldsSingle : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Create non-generic RedbObject with base fields only (no Props rows) var obj = new RedbObject { name = $"BaseFields_Example_{DateTime.UtcNow.Ticks}", value_string = "Example String Value", value_long = 12345, value_bool = true, value_double = 3.14159, value_datetime = DateTime.UtcNow, value_numeric = 99.99m }; // Save - no _values table involved, only _objects var id = await redb.SaveAsync(obj); // Load back var loaded = (await redb.LoadAsync(new[] { id })).FirstOrDefault(); sw.Stop(); if (loaded == null) { return Fail("E164", "Base Fields - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to load saved object."); } var result = Ok("E164", "Base Fields - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"ID: {id}, Name: {loaded.Name}", $"value_string: {loaded.ValueString}", $"value_long: {loaded.ValueLong}, value_bool: {loaded.ValueBool}"]); // Cleanup await redb.DeleteAsync(id); return result; } } Path: redb/redb.Examples/Examples/E165_BaseFieldsBatch.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E165_BaseFieldsBatch.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates batch save/load of non-generic RedbObject with base fields. /// Efficient for bulk operations on simple objects without Props. /// All data stored in _objects table - no props rows. /// [ExampleMeta("E165", "Base Fields - Batch Operations", "Core", ExampleTier.Free, 165, "BaseFields", "Batch", "NonGeneric", RelatedApis = ["RedbObject", "IRedbService.SaveAsync"])] public class E165_BaseFieldsBatch : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Create batch of non-generic objects var objects = new List(); var batchId = DateTime.UtcNow.Ticks; for (int i = 0; i < 1000; i++) { objects.Add(new RedbObject { name = $"Batch_BaseFields_{batchId}_{i}", value_string = $"Item_{i}", value_long = i * 100, value_bool = i % 2 == 0 }); } // Batch save (cast to IRedbObject for batch API) var ids = await redb.SaveAsync(objects.Cast()); // Batch load var loaded = await redb.LoadAsync(ids); sw.Stop(); if (loaded.Count != 1000) { return Fail("E165", "Base Fields - Batch Operations", ExampleTier.Free, sw.ElapsedMilliseconds, $"Expected 1000 objects, got {loaded.Count}."); } // Verify data integrity var verified = loaded.All(x => x.ValueString != null && x.ValueString.StartsWith("Item_")); var result = Ok("E165", "Base Fields - Batch Operations", ExampleTier.Free, sw.ElapsedMilliseconds, loaded.Count, [$"Saved and loaded: {loaded.Count} objects", $"IDs: [{string.Join(", ", ids.Take(3))}...]", $"Data verified: {verified}"]); // Cleanup: one delete for the whole batch await redb.DeleteAsync(ids); return result; } } Path: redb/redb.Examples/Examples/E166_GenericNullProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E166_GenericNullProps.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates using generic RedbObject<TProps> with Props=null. /// Useful when you need scheme association but don't need Props values. /// Only base fields are stored - Props is explicitly null. /// [ExampleMeta("E166", "Generic with Props=null", "Core", ExampleTier.Free, 166, "Generic", "NullProps", "BaseFields", RelatedApis = ["RedbObject", "IRedbService.SaveAsync"])] public class E166_GenericNullProps : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Schemes are synced at startup; read from the scheme cache var scheme = (await redb.GetSchemeByTypeAsync())!; // Create generic object but with Props=null (only base fields) var obj = new RedbObject { name = $"GenericNullProps_{DateTime.UtcNow.Ticks}", scheme_id = scheme.Id, value_string = "MetadataOnly", value_long = 999, value_bool = true }; obj.Props = null!; // Explicitly null - no Props values // Save via interface (triggers non-Props save path) var id = await redb.SaveAsync((IRedbObject)obj); // Load as base IRedbObject (not generic) var loaded = (await redb.LoadAsync(new[] { id })).FirstOrDefault(); sw.Stop(); if (loaded == null) { return Fail("E166", "Generic with Props=null", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to load saved object."); } var result = Ok("E166", "Generic with Props=null", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"ID: {id}, SchemeId: {loaded.SchemeId}", $"value_string: {loaded.ValueString}", $"value_long: {loaded.ValueLong} (no Props values)"]); // Cleanup await redb.DeleteAsync(id); return result; } } Path: redb/redb.Examples/Examples/E167_MixedBatch.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E167_MixedBatch.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates mixed batch save with both non-generic RedbObject and generic RedbObject<T> with Props=null. /// Shows flexibility of REDB to handle different object types in single batch operation. /// [ExampleMeta("E167", "Mixed Batch - Generic and Non-Generic", "Core", ExampleTier.Free, 167, "Mixed", "Batch", "NonGeneric", "Generic", RelatedApis = ["RedbObject", "RedbObject", "IRedbService.SaveAsync"])] public class E167_MixedBatch : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var batchId = DateTime.UtcNow.Ticks; var objects = new List(); // Add non-generic objects objects.Add(new RedbObject { name = $"Mixed_NonGeneric_1_{batchId}", value_string = "NonGeneric", value_long = 1 }); objects.Add(new RedbObject { name = $"Mixed_NonGeneric_2_{batchId}", value_string = "NonGeneric", value_long = 2 }); // Add generic objects with Props=null var scheme = (await redb.GetSchemeByTypeAsync())!; var gen1 = new RedbObject { name = $"Mixed_Generic_1_{batchId}", scheme_id = scheme.Id, value_string = "Generic", value_long = 3 }; gen1.Props = null!; objects.Add(gen1); var gen2 = new RedbObject { name = $"Mixed_Generic_2_{batchId}", scheme_id = scheme.Id, value_string = "Generic", value_long = 4 }; gen2.Props = null!; objects.Add(gen2); // Batch save mixed types var ids = await redb.SaveAsync(objects); // Batch load var loaded = await redb.LoadAsync(ids); sw.Stop(); if (loaded.Count != 4) { return Fail("E167", "Mixed Batch - Generic and Non-Generic", ExampleTier.Free, sw.ElapsedMilliseconds, $"Expected 4 objects, got {loaded.Count}."); } var nonGenCount = loaded.Count(x => x.ValueString == "NonGeneric"); var genCount = loaded.Count(x => x.ValueString == "Generic"); var result = Ok("E167", "Mixed Batch - Generic and Non-Generic", ExampleTier.Free, sw.ElapsedMilliseconds, loaded.Count, [$"Total: {loaded.Count} objects", $"Non-Generic: {nonGenCount}, Generic: {genCount}", $"IDs: [{string.Join(", ", ids)}]"]); // Cleanup: one delete for the whole batch await redb.DeleteAsync(ids); return result; } } Path: redb/redb.Examples/Examples/E168_ArrayContains.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E168_ArrayContains.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates filtering by array element using Contains(). /// Server-side: = ANY(pvt."Skills") in PostgreSQL, STRING_SPLIT in MSSQL. /// Pro feature: array operations in PVT. /// [ExampleMeta("E168", "Array - Contains", "Query", ExampleTier.Free, 168, "Array", "Contains", "Filter", RelatedApis = ["IRedbQueryable.Where", "Array.Contains"])] public class E168_ArrayContains : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees who have "C#" skill var query = redb.Query() .Where(e => e.Skills != null && e.Skills.Contains("C#")) .Take(100); // Uncomment to see generated SQL (contains ANY or STRING_SPLIT): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.Skills != null && e.Skills.Contains("C#")) .CountAsync(); sw.Stop(); var skillSamples = results.Take(3) .Select(e => $"{e.Props.FirstName}: [{string.Join(", ", e.Props.Skills?.Take(3) ?? [])}]"); return Ok("E168", "Array - Contains", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Filter: Skills.Contains(\"C#\")", $"Found: {totalCount} employees", $"Samples: {string.Join("; ", skillSamples)}"]); } } Path: redb/redb.Examples/Examples/E169_ArrayContainsOr.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E169_ArrayContainsOr.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates filtering by multiple array elements using Contains with OR. /// Finds employees who have any of the specified skills. /// Pro feature: multiple array operations in single query. /// [ExampleMeta("E169", "Array - Contains OR", "Query", ExampleTier.Free, 169, "Array", "Contains", "OR", RelatedApis = ["IRedbQueryable.Where", "Array.Contains"])] public class E169_ArrayContainsOr : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees who have C# OR Python skill var query = redb.Query() .Where(e => e.Skills != null && (e.Skills.Contains("C#") || e.Skills.Contains("Python"))) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.Skills != null && (e.Skills.Contains("C#") || e.Skills.Contains("Python"))) .CountAsync(); sw.Stop(); var csharpCount = results.Count(e => e.Props.Skills?.Contains("C#") == true); var pythonCount = results.Count(e => e.Props.Skills?.Contains("Python") == true); return Ok("E169", "Array - Contains OR", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Filter: Skills.Contains(\"C#\") OR Skills.Contains(\"Python\")", $"Found: {totalCount} employees", $"C# devs: {csharpCount}, Python devs: {pythonCount}"]); } } Path: redb/redb.Examples/Examples/E170_ArrayContainsAnd.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E170_ArrayContainsAnd.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates filtering by multiple array elements using Contains with AND. /// Finds employees who have ALL of the specified skills. /// Pro feature: multiple array operations with AND logic. /// [ExampleMeta("E170", "Array - Contains AND", "Query", ExampleTier.Free, 170, "Array", "Contains", "AND", RelatedApis = ["IRedbQueryable.Where", "Array.Contains"])] public class E170_ArrayContainsAnd : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees who have BOTH C# AND SQL skills (full-stack) var query = redb.Query() .Where(e => e.Skills != null && e.Skills.Contains("C#") && e.Skills.Contains("SQL")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.Skills != null && e.Skills.Contains("C#") && e.Skills.Contains("SQL")) .CountAsync(); sw.Stop(); var skillSamples = results.Take(3) .Select(e => $"{e.Props.FirstName}: [{string.Join(", ", e.Props.Skills ?? [])}]"); return Ok("E170", "Array - Contains AND", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Filter: Skills.Contains(\"C#\") AND Skills.Contains(\"SQL\")", $"Found: {totalCount} full-stack employees", $"Samples: {string.Join("; ", skillSamples)}"]); } } Path: redb/redb.Examples/Examples/E171_ScalarPlusArray.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E171_ScalarPlusArray.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates combining scalar field filter with array Contains filter. /// Finds senior developers (Age > 30) who have specific skills. /// Pro feature: mixed scalar and array expressions in single query. /// [ExampleMeta("E171", "Scalar + Array Combined", "Query", ExampleTier.Free, 171, "Array", "Scalar", "Combined", RelatedApis = ["IRedbQueryable.Where", "Array.Contains"])] public class E171_ScalarPlusArray : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find senior developers: Age > 30 AND has C# skill var query = redb.Query() .Where(e => e.Age > 30 && e.Skills != null && e.Skills.Contains("C#")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.Age > 30 && e.Skills != null && e.Skills.Contains("C#")) .CountAsync(); sw.Stop(); var avgAge = results.Any() ? results.Average(e => e.Props.Age) : 0; var sample = results.FirstOrDefault(); return Ok("E171", "Scalar + Array Combined", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Filter: Age > 30 AND Skills.Contains(\"C#\")", $"Found: {totalCount} senior C# developers", $"Avg age: {avgAge:F1}, Sample: {sample?.Props.FirstName} ({sample?.Props.Age})"]); } } Path: redb/redb.Examples/Examples/E172_StringLength.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E172_StringLength.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates String.Length property in Where clause. /// Server-side: LENGTH() in PostgreSQL, LEN() in MSSQL. /// Pro feature: string property access in expressions. /// [ExampleMeta("E172", "String.Length Filter", "Query", ExampleTier.Free, 172, "String", "Length", "Property", RelatedApis = ["IRedbQueryable.Where", "String.Length"])] public class E172_StringLength : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees with long last names (> 6 characters) var query = redb.Query() .Where(e => e.LastName.Length > 6) .Take(100); // Uncomment to see generated SQL (contains LENGTH or LEN): // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var results = await query.ToListAsync(); var totalCount = await redb.Query() .Where(e => e.LastName.Length > 6) .CountAsync(); sw.Stop(); var names = results.Take(5) .Select(e => $"{e.Props.LastName} ({e.Props.LastName.Length} chars)"); return Ok("E172", "String.Length Filter", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Filter: LastName.Length > 6", $"Found: {totalCount} employees", $"Samples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/Examples/E173_TreeQueryGroupBy.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E173_TreeQueryGroupBy.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates GroupBy aggregation on TreeQuery. /// Groups tree nodes and calculates aggregates (SUM, COUNT) within tree context. /// Pro feature: TreeQuery + GroupBy for hierarchical data analysis. /// [ExampleMeta("E173", "TreeQuery - GroupBy", "Tree", ExampleTier.Free, 173, "Tree", "GroupBy", "Aggregation", RelatedApis = ["ITreeQueryable.GroupBy", "Agg.Sum", "Agg.Count"])] public class E173_TreeQueryGroupBy : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E173", "TreeQuery - GroupBy", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Group departments by IsActive status and aggregate budget var groupedQuery = redb.TreeQuery(root.Id) .Where(d => d.Budget > 0) .GroupBy(d => d.IsActive); // Uncomment to see generated SQL: // var sql = await groupedQuery.ToSqlStringAsync(g => new { // IsActive = g.Key, // TotalBudget = Agg.Sum(g, d => d.Budget), // Count = Agg.Count(g) // }); // Console.WriteLine(sql); var results = await groupedQuery.SelectAsync(g => new { IsActive = g.Key, TotalBudget = Agg.Sum(g, d => d.Budget), DeptCount = Agg.Count(g) }); sw.Stop(); var output = results.Select(r => $"Active={r.IsActive}: {r.DeptCount} depts, Budget=${r.TotalBudget:N0}").ToArray(); return Ok("E173", "TreeQuery - GroupBy", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, output.Prepend($"Groups: {results.Count}").ToArray()); } } Path: redb/redb.Examples/Examples/E174_TreeQueryWindow.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E174_TreeQueryWindow.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates Window Functions on TreeQuery. /// Calculates ROW_NUMBER and running totals within tree hierarchy. /// Pro feature: TreeQuery + Window for hierarchical rankings and cumulative values. /// [ExampleMeta("E174", "TreeQuery - Window Functions", "Tree", ExampleTier.Free, 174, "Tree", "Window", "RowNumber", "RunningSum", RelatedApis = ["ITreeQueryable.WithWindow", "Win.RowNumber", "Win.Sum"])] public class E174_TreeQueryWindow : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E174", "TreeQuery - Window Functions", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Window functions on tree: rank departments by budget within the hierarchy var windowQuery = redb.TreeQuery(root.Id) .Where(d => d.Budget > 0) .Take(20) .WithWindow(w => w .PartitionBy(d => d.IsActive) .OrderByDesc(d => d.Budget)); // Uncomment to see generated SQL: // var sql = await windowQuery.ToSqlStringAsync(d => new { // d.Props.Name, // d.Props.Budget, // Rank = Win.RowNumber(), // RunningBudget = Win.Sum(d.Props.Budget) // }); // Console.WriteLine(sql); var results = await windowQuery.SelectAsync(d => new { Name = d.Props.Name, Budget = d.Props.Budget, IsActive = d.Props.IsActive, Rank = Win.RowNumber(), RunningBudget = Win.Sum(d.Props.Budget) }); sw.Stop(); var output = results.Take(5).Select(r => $"#{r.Rank} {r.Name}: ${r.Budget:N0} (Running: ${r.RunningBudget:N0})").ToArray(); return Ok("E174", "TreeQuery - Window Functions", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, output.Prepend($"Total: {results.Count} departments ranked").ToArray()); } } Path: redb/redb.Examples/Examples/E175_TreeQueryGroupByWindow.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E175_TreeQueryGroupByWindow.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Core.Query.Window; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates GroupBy + Window Functions on TreeQuery. /// First groups tree nodes, then applies window functions to rank the groups. /// Pro feature: TreeQuery + GroupBy + Window for advanced hierarchical analytics. /// [ExampleMeta("E175", "TreeQuery - GroupBy + Window", "Tree", ExampleTier.Pro, 175, "Tree", "GroupBy", "Window", "Combined", RelatedApis = ["ITreeQueryable.GroupBy", "IGroupedQueryable.WithWindow", "Win.RowNumber"])] public class E175_TreeQueryGroupByWindow : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E175", "TreeQuery - GroupBy + Window", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // GroupBy + Window: group by IsActive, then rank groups by total budget var groupedWindowQuery = redb.TreeQuery(root.Id) .Where(d => d.Budget > 0) .GroupBy(d => d.IsActive) .WithWindow(w => w .OrderByDesc(g => Agg.Sum(g, d => d.Budget))); // Uncomment to see generated SQL: // var sql = await groupedWindowQuery.ToSqlStringAsync(g => new { // IsActive = g.Key, // TotalBudget = Agg.Sum(g, d => d.Budget), // DeptCount = Agg.Count(g), // Rank = Win.RowNumber() // }); // Console.WriteLine(sql); var results = await groupedWindowQuery.SelectAsync(g => new { IsActive = g.Key, TotalBudget = Agg.Sum(g, d => d.Budget), DeptCount = Agg.Count(g), Rank = Win.RowNumber() }); sw.Stop(); var output = results.Select(r => $"#{r.Rank} Active={r.IsActive}: {r.DeptCount} depts, Total=${r.TotalBudget:N0}").ToArray(); return Ok("E175", "TreeQuery - GroupBy + Window", ExampleTier.Pro, sw.ElapsedMilliseconds, results.Count, output.Prepend($"Groups ranked by budget: {results.Count}").ToArray()); } } Path: redb/redb.Examples/Examples/E176_TreeDistinctBy.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E176_TreeDistinctBy.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates DistinctBy on TreeQuery to get unique tree nodes by a Props field. /// Useful for removing duplicates based on specific property values. /// Pro feature: DistinctBy with tree context. /// [ExampleMeta("E176", "TreeQuery - DistinctBy", "Tree", ExampleTier.Pro, 176, "Tree", "DistinctBy", "Unique", RelatedApis = ["ITreeQueryable.DistinctBy"])] public class E176_TreeDistinctBy : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E176", "TreeQuery - DistinctBy", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Get total count before distinct var totalCount = await redb.TreeQuery(root.Id).CountAsync(); // Get unique departments by IsActive status (will return max 2: true and false) var query = redb.TreeQuery(root.Id) .DistinctBy(d => d.IsActive) .Take(100); // Uncomment to see generated SQL: //var sql = query.ToSqlString(); //Console.WriteLine(sql); var uniqueByStatus = await query.ToListAsync(); sw.Stop(); var statuses = uniqueByStatus.Select(d => $"IsActive={d.Props.IsActive}"); return Ok("E176", "TreeQuery - DistinctBy", ExampleTier.Pro, sw.ElapsedMilliseconds, uniqueByStatus.Count, [$"DistinctBy(IsActive) on {totalCount} nodes", $"Unique statuses: {uniqueByStatus.Count}", $"Values: {string.Join(", ", statuses)}"]); } } Path: redb/redb.Examples/Examples/E177_TreeDistinctByRedb.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E177_TreeDistinctByRedb.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates DistinctByRedb on TreeQuery to get unique tree nodes by a base field. /// Uses _objects table fields directly (no props join) - highly optimized. /// Pro feature: DistinctByRedb with tree context. /// [ExampleMeta("E177", "TreeQuery - DistinctByRedb", "Tree", ExampleTier.Pro, 177, "Tree", "DistinctByRedb", "BaseField", RelatedApis = ["ITreeQueryable.DistinctByRedb"])] public class E177_TreeDistinctByRedb : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E177", "TreeQuery - DistinctByRedb", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Get total count before distinct var totalCount = await redb.TreeQuery(root.Id).CountAsync(); // Get unique departments by ParentId (base field) - shows unique parent branches var query = redb.TreeQuery(root.Id) .DistinctByRedb(d => d.ParentId) .Take(20); // Uncomment to see generated SQL (no _values JOIN): // var sql = query.ToSqlString(); // Console.WriteLine(sql); var uniqueByParent = await query.ToListAsync(); sw.Stop(); var parentIds = uniqueByParent.Take(5).Select(d => d.parent_id?.ToString() ?? "null"); return Ok("E177", "TreeQuery - DistinctByRedb", ExampleTier.Pro, sw.ElapsedMilliseconds, uniqueByParent.Count, [$"DistinctByRedb(ParentId) on {totalCount} nodes", $"Unique parents: {uniqueByParent.Count}", $"Sample ParentIds: {string.Join(", ", parentIds)}"]); } } Path: redb/redb.Examples/Examples/E178_TreeOrderBy.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E178_TreeOrderBy.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates OrderBy on TreeQuery to sort tree nodes by a Props field. /// Ascending order by department Code. /// Pro feature: OrderBy with tree context. /// [ExampleMeta("E178", "TreeQuery - OrderBy", "Tree", ExampleTier.Free, 178, "Tree", "OrderBy", "Sort", "Ascending", RelatedApis = ["ITreeQueryable.OrderBy"])] public class E178_TreeOrderBy : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E178", "TreeQuery - OrderBy", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Sort departments by Code (ascending) var query = redb.TreeQuery(root.Id) .OrderBy(d => d.Code) .Take(100); // Uncomment to see generated SQL: // var sql = query.ToSqlString(); // Console.WriteLine(sql); var sorted = await query.ToListAsync(); sw.Stop(); var codes = sorted.Take(5).Select(d => d.Props.Code); return Ok("E178", "TreeQuery - OrderBy", ExampleTier.Free, sw.ElapsedMilliseconds, sorted.Count, [$"OrderBy(Code) ascending", $"Loaded: {sorted.Count} departments", $"First codes: {string.Join(", ", codes)}"]); } } Path: redb/redb.Examples/Examples/E179_TreeOrderByDescending.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E179_TreeOrderByDescending.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates OrderByDescending on TreeQuery to sort tree nodes in reverse order. /// Descending order by Budget - highest budgets first. /// Pro feature: OrderByDescending with tree context. /// [ExampleMeta("E179", "TreeQuery - OrderByDescending", "Tree", ExampleTier.Free, 179, "Tree", "OrderByDescending", "Sort", "Descending", RelatedApis = ["ITreeQueryable.OrderByDescending"])] public class E179_TreeOrderByDescending : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E179", "TreeQuery - OrderByDescending", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Sort departments by Budget (descending) - highest first var query = redb.TreeQuery(root.Id) .Where(d => d.Budget > 0) .OrderByDescending(d => d.Budget) .Take(100); // Uncomment to see generated SQL: // var sql = query.ToSqlString(); // Console.WriteLine(sql); var sorted = await query.ToListAsync(); sw.Stop(); var topBudgets = sorted.Take(5).Select(d => $"{d.Props.Name}: ${d.Props.Budget:N0}"); return Ok("E179", "TreeQuery - OrderByDescending", ExampleTier.Free, sw.ElapsedMilliseconds, sorted.Count, [$"OrderByDescending(Budget) - highest first", $"Loaded: {sorted.Count} departments", $"Top: {string.Join(", ", topBudgets)}"]); } } Path: redb/redb.Examples/Examples/E180_TreeDistinctByOrderBy.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E180_TreeDistinctByOrderBy.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates combining DistinctBy and OrderByDescending on TreeQuery. /// Gets unique values by one field, sorted by another. /// Pro feature: chained tree query operations. /// [ExampleMeta("E180", "TreeQuery - DistinctBy + OrderBy", "Tree", ExampleTier.Pro, 180, "Tree", "DistinctBy", "OrderBy", "Combined", RelatedApis = ["ITreeQueryable.DistinctBy", "ITreeQueryable.OrderByDescending"])] public class E180_TreeDistinctByOrderBy : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Ensure tree data exists (from E089_TreeCreate) var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E180", "TreeQuery - DistinctBy + OrderBy", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree data found. Please run E089_TreeCreate first."); } // Get unique by IsActive, then sort by Budget descending var query = redb.TreeQuery(root.Id) .Where(d => d.Budget > 0) .DistinctBy(d => d.IsActive) .OrderByDescending(d => d.Budget) .Take(100); // Uncomment to see generated SQL: //var sql = query.ToSqlString(); //Console.WriteLine(sql); var results = await query.ToListAsync(); sw.Stop(); var output = results.Select(d => $"Active={d.Props.IsActive}, Budget=${d.Props.Budget:N0}"); return Ok("E180", "TreeQuery - DistinctBy + OrderBy", ExampleTier.Pro, sw.ElapsedMilliseconds, results.Count, [$"DistinctBy(IsActive) + OrderByDescending(Budget)", $"Results: {results.Count}", string.Join("; ", output)]); } } Path: redb/redb.Examples/Examples/E181_DeleteSingle.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E181_DeleteSingle.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates deleting a single object by ID. /// Creates a temporary object, then deletes it. /// [ExampleMeta("E181", "Delete - Single Object", "CRUD", ExampleTier.Free, 181, "Delete", "Single", "Remove", RelatedApis = ["IRedbService.DeleteAsync"])] public class E181_DeleteSingle : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Create a temporary object to delete var scheme = (await redb.GetSchemeByTypeAsync())!; var tempObj = new RedbObject { name = $"ToDelete_{DateTime.UtcNow.Ticks}", scheme_id = scheme.Id, Props = new EmployeeProps { FirstName = "Temporary", LastName = "Employee", Age = 25, Salary = 50000m, Department = "Test" } }; var id = await redb.SaveAsync(tempObj); // Verify it exists var beforeDelete = await redb.LoadAsync(id); var existsBefore = beforeDelete != null; // Delete the object await redb.DeleteAsync(id); // Verify it's deleted var afterDelete = await redb.LoadAsync(id); var existsAfter = afterDelete != null; sw.Stop(); if (!existsBefore || existsAfter) { return Fail("E181", "Delete - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, $"Delete verification failed. Before: {existsBefore}, After: {existsAfter}"); } return Ok("E181", "Delete - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Created object ID: {id}", $"Existed before delete: {existsBefore}", $"Existed after delete: {existsAfter}"]); } } Path: redb/redb.Examples/Examples/E182_DeleteBatch.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E182_DeleteBatch.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates batch deletion of multiple objects. /// Creates temporary objects, then deletes them all at once. /// [ExampleMeta("E182", "Delete - Batch", "Core", ExampleTier.Free, 182, "Delete", "Batch", "Multiple", RelatedApis = ["IRedbService.DeleteAsync"])] public class E182_DeleteBatch : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Create temporary objects to delete var scheme = (await redb.GetSchemeByTypeAsync())!; var batchId = DateTime.UtcNow.Ticks; var tempObjects = new List>(); for (int i = 0; i < 5; i++) { tempObjects.Add(new RedbObject { name = $"BatchDelete_{batchId}_{i}", scheme_id = scheme.Id, Props = new EmployeeProps { FirstName = $"Temp{i}", LastName = "Employee", Age = 20 + i, Salary = 40000m + i * 1000, Department = "Test" } }); } // Save all var ids = await redb.SaveAsync(tempObjects.Cast()); // Verify count before delete var countBefore = (await redb.LoadAsync(ids)).Count; // Delete all by IDs in one call await redb.DeleteAsync(ids); // Verify count after delete var countAfter = (await redb.LoadAsync(ids)).Count; sw.Stop(); return Ok("E182", "Delete - Batch", ExampleTier.Free, sw.ElapsedMilliseconds, ids.Count, [$"Created: {ids.Count} objects", $"Before delete: {countBefore}", $"After delete: {countAfter}"]); } } Path: redb/redb.Examples/Examples/E183_FirstOrDefaultAsync.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E183_FirstOrDefaultAsync.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates FirstOrDefaultAsync to get a single object matching criteria. /// Returns the first match or null if none found. /// [ExampleMeta("E183", "FirstOrDefaultAsync", "Query", ExampleTier.Free, 183, "First", "Single", "Query", RelatedApis = ["IRedbQueryable.FirstOrDefaultAsync"])] public class E183_FirstOrDefaultAsync : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Get first employee with salary > 80000 var highEarner = await redb.Query() .Where(e => e.Salary > 80000m) .OrderByDescending(e => e.Salary) .FirstOrDefaultAsync(); // Get first with impossible condition (should be null) var notFound = await redb.Query() .Where(e => e.Salary > 10_000_000m) .FirstOrDefaultAsync(); sw.Stop(); if (highEarner == null) { return Fail("E183", "FirstOrDefaultAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No employees with salary > 80000 found."); } return Ok("E183", "FirstOrDefaultAsync", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"First high earner: {highEarner.Props.FirstName} {highEarner.Props.LastName}", $"Salary: ${highEarner.Props.Salary:N0}", $"Not found (null): {notFound == null}"]); } } Path: redb/redb.Examples/Examples/E184_WhereNullable.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E184_WhereNullable.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates filtering by nullable fields. /// Finds objects where a nullable field is null or has value. /// [ExampleMeta("E184", "Where - Nullable Field", "Query", ExampleTier.Free, 184, "Where", "Nullable", "Null", "HasValue", RelatedApis = ["IRedbQueryable.Where"])] public class E184_WhereNullable : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Find employees where EmployeeCode is null var withoutCode = await redb.Query() .Where(e => e.EmployeeCode == null) .Take(5) .ToListAsync(); var nullCount = await redb.Query() .Where(e => e.EmployeeCode == null) .CountAsync(); // Find employees where EmployeeCode is NOT null var withCode = await redb.Query() .Where(e => e.EmployeeCode != null) .Take(5) .ToListAsync(); var notNullCount = await redb.Query() .Where(e => e.EmployeeCode != null) .CountAsync(); sw.Stop(); var sampleCode = withCode.FirstOrDefault()?.Props?.EmployeeCode ?? "N/A"; return Ok("E184", "Where - Nullable Field", ExampleTier.Free, sw.ElapsedMilliseconds, nullCount + notNullCount, [$"EmployeeCode == null: {nullCount}", $"EmployeeCode != null: {notNullCount}", $"Sample code: {sampleCode}"]); } } Path: redb/redb.Examples/Examples/E185_WhereBool.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E185_WhereBool.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates filtering by conditions that can be simplified. /// Shows different ways to filter including combined conditions. /// [ExampleMeta("E185", "Where - Combined Conditions", "Query", ExampleTier.Free, 185, "Where", "Combined", "Multiple", RelatedApis = ["IRedbQueryable.Where"])] public class E185_WhereBool : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Combined conditions: Age > 30 AND Salary > 70000 var expHighEarnersCount = await redb.Query() .Where(e => e.Age > 30 && e.Salary > 70000m) .CountAsync(); var expHighEarners = await redb.Query() .Where(e => e.Age > 30 && e.Salary > 70000m) .Take(5) .ToListAsync(); // OR conditions: Department == "IT" OR Department == "Engineering" var techDeptCount = await redb.Query() .Where(e => e.Department == "IT" || e.Department == "Engineering") .CountAsync(); sw.Stop(); var names = expHighEarners.Take(3).Select(e => $"{e.Props.FirstName} ({e.Props.Age}, ${e.Props.Salary:N0})"); return Ok("E185", "Where - Combined Conditions", ExampleTier.Free, sw.ElapsedMilliseconds, expHighEarnersCount + techDeptCount, [$"Age > 30 AND Salary > 70000: {expHighEarnersCount}", $"IT OR Engineering: {techDeptCount}", $"Samples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/Examples/E186_ObjectReference.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E186_ObjectReference.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates loading objects with RedbObject references. /// EmployeeProps has CurrentProject field of type RedbObject<ProjectMetricsProps>. /// Shows how referenced objects are loaded. /// [ExampleMeta("E186", "Object Reference - Load", "Core", ExampleTier.Free, 186, "Reference", "Related", "Nested", RelatedApis = ["RedbObject"])] public class E186_ObjectReference : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Schemes are synced at startup; read from the scheme cache var projectScheme = (await redb.GetSchemeByTypeAsync())!; var employeeScheme = (await redb.GetSchemeByTypeAsync())!; // Create a project var project = new RedbObject { name = $"RefProject_{DateTime.UtcNow.Ticks}", scheme_id = projectScheme.Id, Props = new ProjectMetricsProps { ProjectId = 1001, TasksCompleted = 50, TasksTotal = 100, Budget = 500000 } }; var id1 = await redb.SaveAsync(project); //Console.WriteLine($"First object id: {id1}"); // Create employee with project reference var employee = new RedbObject { name = $"RefEmployee_{DateTime.UtcNow.Ticks}", scheme_id = employeeScheme.Id, Props = new EmployeeProps { FirstName = "John", LastName = "ProjectManager", Age = 35, Salary = 90000m, Department = "Engineering", CurrentProject = project // Reference to another RedbObject } }; var id2 = await redb.SaveAsync(employee); //Console.WriteLine($"Second object id: {id2}"); // Load employee and access referenced project var loaded = await redb.LoadAsync(employee.Id); sw.Stop(); if (loaded?.Props?.CurrentProject == null) { // Cleanup await redb.DeleteAsync(employee.Id); await redb.DeleteAsync(project.Id); return Fail("E186", "Object Reference - Load", ExampleTier.Free, sw.ElapsedMilliseconds, "CurrentProject reference not loaded."); } var projName = loaded.Props.CurrentProject.name; var projBudget = loaded.Props.CurrentProject.Props?.Budget ?? 0; // Cleanup await redb.DeleteAsync(employee.Id); await redb.DeleteAsync(project.Id); return Ok("E186", "Object Reference - Load", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Employee: {loaded.Props.FirstName} {loaded.Props.LastName}", $"Project: {projName}", $"Project Budget: ${projBudget:N0}"]); } } Path: redb/redb.Examples/Examples/E187_UpdateExisting.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E187_UpdateExisting.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Demonstrates updating an existing object by loading, modifying, and saving it. /// Shows the standard update pattern in REDB: Load -> Modify -> Save. /// [ExampleMeta("E187", "Update - Existing Object", "CRUD", ExampleTier.Free, 187, "Update", "Modify", "Save", RelatedApis = ["IRedbService.LoadAsync", "IRedbService.SaveAsync"])] public class E187_UpdateExisting : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Create an object to update var scheme = (await redb.GetSchemeByTypeAsync())!; var original = new RedbObject { name = $"ToUpdate_{DateTime.UtcNow.Ticks}", scheme_id = scheme.Id, Props = new EmployeeProps { FirstName = "Original", LastName = "Name", Age = 30, Salary = 60000m, Department = "Sales" } }; await redb.SaveAsync(original); var originalSalary = original.Props.Salary; // Load the object var loaded = await redb.LoadAsync(original.Id); if (loaded == null) { sw.Stop(); return Fail("E187", "Update - Existing Object", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to load object for update."); } // Modify Props loaded.Props.FirstName = "Updated"; loaded.Props.Salary = 75000m; // Raise! loaded.Props.Department = "Engineering"; // Save changes (same ID = update) await redb.SaveAsync(loaded); // Verify changes var verified = await redb.LoadAsync(original.Id); sw.Stop(); // Cleanup await redb.DeleteAsync(original.Id); if (verified == null) { return Fail("E187", "Update - Existing Object", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to verify updated object."); } return Ok("E187", "Update - Existing Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Original: FirstName='Original', Salary=${originalSalary:N0}", $"Updated: FirstName='{verified.Props.FirstName}', Salary=${verified.Props.Salary:N0}", $"Department changed: Sales -> {verified.Props.Department}"]); } } Path: redb/redb.Examples/Examples/E188_SoftDeleteReference.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E188_SoftDeleteReference.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Verifies the soft-delete read-path fix (_id_scheme = -10). /// /// A surviving Employee references a Project via the RedbObject _Object edge /// (EmployeeProps.CurrentProject). When the Project is **soft-deleted** /// (moved to trash, _id_scheme = -10 — NOT purged), loading the Employee must /// NOT materialize the tombstone through the nested reference. /// /// Invariant checked (edition-agnostic): /// loaded.CurrentProject?.Props == null /// Free nulls the reference outright (get_object_json returns NULL for the /// trashed target); Pro leaves an id-only placeholder with Props == null /// (the trashed target is filtered out of Materialization_SelectObjectsByIds, /// so it is never substituted). Either way the trashed object is not loaded as /// live data. The _values._Object pointer is left intact, so the reference /// returns once the target is restored from trash. /// [ExampleMeta("E188", "Soft-Delete - Nested Reference Not Materialized", "Core", ExampleTier.Free, 188, "SoftDelete", "Reference", "Trash", "-10", RelatedApis = ["IRedbService.SoftDeleteAsync", "RedbObject"])] public class E188_SoftDeleteReference : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var projectScheme = (await redb.GetSchemeByTypeAsync())!; var employeeScheme = (await redb.GetSchemeByTypeAsync())!; // Project that the employee will reference. var project = new RedbObject { name = $"SD_Project_{DateTime.UtcNow.Ticks}", scheme_id = projectScheme.Id, Props = new ProjectMetricsProps { ProjectId = 2001, TasksCompleted = 10, TasksTotal = 20, Budget = 250000 } }; await redb.SaveAsync(project); // Surviving employee with an _Object reference to the project. var employee = new RedbObject { name = $"SD_Employee_{DateTime.UtcNow.Ticks}", scheme_id = employeeScheme.Id, Props = new EmployeeProps { FirstName = "Jane", LastName = "Survivor", Age = 40, Salary = 95000m, Department = "Engineering", CurrentProject = project } }; await redb.SaveAsync(employee); // Sanity: before soft-delete the nested reference materializes fully. var before = await redb.LoadAsync(employee.Id); var beforeOk = before?.Props?.CurrentProject?.Props != null; // Soft-delete the referenced project: it moves to trash (_id_scheme = -10), // it is NOT physically purged, and the _values._Object pointer stays intact. await redb.SoftDeleteAsync(new[] { project.Id }); // Reload the survivor (cache is off in the examples, so this re-materializes). var after = await redb.LoadAsync(employee.Id); var nested = after?.Props?.CurrentProject; var tombstoneLeaked = nested?.Props != null; // trashed object materialized as live data var placeholderLeaked = nested != null; // id-only placeholder left behind (no Free/Pro parity) sw.Stop(); // Cleanup: drop the survivor first (removes the _Object pointer), then the // trashed project (now unreferenced, so the hard delete is unblocked). await redb.DeleteAsync(employee.Id); await redb.DeleteAsync(project.Id); if (!beforeOk) { return Fail("E188", "Soft-Delete - Nested Reference Not Materialized", ExampleTier.Free, sw.ElapsedMilliseconds, "Sanity check failed: CurrentProject.Props was null BEFORE soft-delete (reference never loaded)."); } if (tombstoneLeaked) { return Fail("E188", "Soft-Delete - Nested Reference Not Materialized", ExampleTier.Free, sw.ElapsedMilliseconds, "REGRESSION: soft-deleted (_id_scheme=-10) project was still materialized through the nested reference."); } if (placeholderLeaked) { return Fail("E188", "Soft-Delete - Nested Reference Not Materialized", ExampleTier.Free, sw.ElapsedMilliseconds, "PARITY GAP: trashed reference left as an id-only placeholder instead of null (Free returns null)."); } return Ok("E188", "Soft-Delete - Nested Reference Not Materialized", ExampleTier.Free, sw.ElapsedMilliseconds, 1, ["Before soft-delete: CurrentProject materialized", "After soft-delete: CurrentProject == null", "Free / Pro parity: reference nulled in both editions"]); } } Path: redb/redb.Examples/Examples/E190_SumAsyncFiltered.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E190_SumAsyncFiltered.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// SumAsync with Where filter applied before aggregation. /// Filter employees by department, then calculate total salary. /// Tests Pro filter handling in Aggregation. /// [ExampleMeta("E190", "SumAsync - With Filter", "Analytics", ExampleTier.Free, 190, "Sum", "Where", "Filter", "Aggregation", RelatedApis = ["IRedbQueryable.SumAsync", "IRedbQueryable.Where"])] public class E190_SumAsyncFiltered : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Uncomment to see generated SQL: //var sql = await redb.Query() // .Where(x => x.Department == "Engineering") // .ToSqlStringAsync(); //Console.WriteLine(sql); // Sum salaries only for Engineering department var engineeringSalary = await redb.Query() .Where(x => x.Department == "Engineering") .SumAsync(x => x.Salary); // Compare with total (no filter) var totalSalary = await redb.Query() .SumAsync(x => x.Salary); // Filter and sum on nested classes: home city one level deep, floor two levels deep var berlinFloors = await redb.Query() .Where(x => x.HomeAddress!.City == "Berlin") .SumAsync(x => x.HomeAddress!.Building!.Floor); sw.Stop(); return Ok("E190", "SumAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Engineering SUM: {engineeringSalary:N0}", $"Total SUM: {totalSalary:N0}", $"Ratio: {(totalSalary > 0 ? engineeringSalary / totalSalary * 100 : 0):F1}%", $"Berlin SUM(HomeAddress.Building.Floor): {berlinFloors:N0}"]); } } Path: redb/redb.Examples/Examples/E191_WindowFiltered.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E191_WindowFiltered.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Window function with Where filter applied before windowing. /// Filter employees by salary threshold, then apply ROW_NUMBER. /// Tests Pro filter handling in Window queries. /// [ExampleMeta("E191", "Window - With Filter", "Analytics", ExampleTier.Free, 191, "Window", "Where", "Filter", "RowNumber", RelatedApis = ["IRedbQueryable.WithWindow", "IRedbQueryable.Where", "Win.RowNumber"])] public class E191_WindowFiltered : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Window with filter: only high earners (Salary > 70000) var windowQuery = redb.Query() .Where(x => x.Salary > 70000m) .Take(20) .WithWindow(w => w .PartitionBy(x => x.Department) .OrderByDesc(x => x.Salary)); // Uncomment to see generated SQL: //var sql = await windowQuery.ToSqlStringAsync(x => new { x.Props.FirstName, Rank = Win.RowNumber() }); //Console.WriteLine(sql); var ranked = await windowQuery.SelectAsync(x => new { Name = x.Props.FirstName, Department = x.Props.Department, Salary = x.Props.Salary, Rank = Win.RowNumber() }); sw.Stop(); var top = ranked.FirstOrDefault(); return Ok("E191", "Window - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, ranked.Count, [$"Filter: Salary > 70k", $"Results: {ranked.Count}", $"#1 in {top?.Department ?? "N/A"}: {top?.Name ?? "N/A"} ({top?.Salary:N0})"]); } } Path: redb/redb.Examples/Examples/E192_AggregateFiltered.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E192_AggregateFiltered.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Multiple aggregations with Where filter applied before aggregation. /// Filter employees by position, then calculate Sum, Avg, Min, Max. /// Tests Pro filter handling in batch Aggregation. /// [ExampleMeta("E192", "AggregateAsync - With Filter", "Analytics", ExampleTier.Free, 192, "Aggregate", "Where", "Filter", "Sum", "Avg", RelatedApis = ["IRedbQueryable.AggregateAsync", "IRedbQueryable.Where"])] public class E192_AggregateFiltered : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Aggregate only Developers var query = redb.Query() .Where(x => x.Position == "Developer" && x.HomeAddress!.City != "Tokyo"); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var stats = await query.AggregateAsync(x => new { TotalSalary = Agg.Sum(x.Props.Salary), AvgSalary = Agg.Average(x.Props.Salary), MinSalary = Agg.Min(x.Props.Salary), MaxSalary = Agg.Max(x.Props.Salary), MinFloor = Agg.Min(x.Props.HomeAddress!.Building!.Floor), MaxFloor = Agg.Max(x.Props.HomeAddress!.Building!.Floor), AvgFloor = Agg.Average(x.Props.HomeAddress!.Building!.Floor), Count = Agg.Count() }); sw.Stop(); return Ok("E192", "AggregateAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [ $"Filter: Position = 'Developer' AND HomeAddress.City != 'Tokyo'", $"Count: {stats?.Count ?? 0}", $"Salary: {stats?.MinSalary:N0} - {stats?.MaxSalary:N0} (Avg: {stats?.AvgSalary:N0})", $"Home floor: {stats?.MinFloor} - {stats?.MaxFloor} (Avg: {stats?.AvgFloor:F2})" ]); } } Path: redb/redb.Examples/Examples/E193_AverageAsyncFiltered.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E193_AverageAsyncFiltered.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// AverageAsync with Where filter applied before aggregation. /// Filter employees by age range, then calculate average salary. /// Tests Pro filter handling in single Aggregation. /// [ExampleMeta("E193", "AverageAsync - With Filter", "Analytics", ExampleTier.Free, 193, "Average", "Where", "Filter", "Aggregation", RelatedApis = ["IRedbQueryable.AverageAsync", "IRedbQueryable.Where"])] public class E193_AverageAsyncFiltered : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Average salary for employees aged 30-40 var avgSalaryMiddle = await redb.Query() .Where(x => x.Age >= 30 && x.Age <= 40) .AverageAsync(x => x.Salary); // Compare with overall average var avgSalaryAll = await redb.Query() .AverageAsync(x => x.Salary); // Filter and average on nested classes: home city one level deep, floor two levels deep var avgFloorLondon = await redb.Query() .Where(x => x.HomeAddress!.City == "London") .AverageAsync(x => x.HomeAddress!.Building!.Floor); sw.Stop(); return Ok("E193", "AverageAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Age 30-40 AVG: {avgSalaryMiddle:N0}", $"All AVG: {avgSalaryAll:N0}", $"London AVG(HomeAddress.Building.Floor): {avgFloorLondon:F2}"]); } } Path: redb/redb.Examples/Examples/E194_MinMaxAsyncFiltered.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E194_MinMaxAsyncFiltered.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// MinAsync/MaxAsync with Where filter applied before aggregation. /// Filter employees by department, then find salary range. /// Tests Pro filter handling in single Aggregation. /// [ExampleMeta("E194", "MinMaxAsync - With Filter", "Analytics", ExampleTier.Free, 194, "Min", "Max", "Where", "Filter", "Aggregation", RelatedApis = ["IRedbQueryable.MinAsync", "IRedbQueryable.MaxAsync", "IRedbQueryable.Where"])] public class E194_MinMaxAsyncFiltered : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Salary range for Sales department only var query = redb.Query() .Where(x => x.Department == "Sales"); var minSalary = await query.MinAsync(x => x.Salary); var maxSalary = await query.MaxAsync(x => x.Salary); // Compare with overall range var minAll = await redb.Query().MinAsync(x => x.Salary); var maxAll = await redb.Query().MaxAsync(x => x.Salary); // Filter and range on nested classes: home city one level deep, floor two levels deep var berlin = redb.Query() .Where(x => x.HomeAddress!.City == "Berlin"); var minFloor = await berlin.MinAsync(x => x.HomeAddress!.Building!.Floor); var maxFloor = await berlin.MaxAsync(x => x.HomeAddress!.Building!.Floor); sw.Stop(); return Ok("E194", "MinMaxAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [ $"Sales: {minSalary:N0} - {maxSalary:N0}", $"All: {minAll:N0} - {maxAll:N0}", $"Berlin HomeAddress.Building.Floor: {minFloor} - {maxFloor}" ]); } } Path: redb/redb.Examples/Examples/E195_GroupByWindowFiltered.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E195_GroupByWindowFiltered.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Query.Aggregation; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// GroupBy + Window with Where filter applied before grouping. /// Filter employees by salary, group by department, then rank groups. /// Tests Pro filter handling in GroupedWindow queries. /// [ExampleMeta("E195", "GroupBy + Window - With Filter", "Analytics", ExampleTier.Pro, 195, "GroupBy", "Window", "Where", "Filter", "Rank", RelatedApis = ["IRedbGroupedQueryable.WithWindow", "IRedbQueryable.Where"])] public class E195_GroupByWindowFiltered : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Filter high earners, group by department, rank by total salary var ranked = await redb.Query() .Where(x => x.Salary > 60000m) .GroupBy(x => x.Department) .WithWindow(w => w.OrderByDesc(g => Agg.Sum(g, x => x.Salary))) .SelectAsync(g => new { Department = g.Key, TotalSalary = Agg.Sum(g, x => x.Salary), Count = Agg.Count(g), Rank = Win.Rank() }); //var sql = await redb.Query() // .Where(x => x.Salary > 60000m) // .GroupBy(x => x.Department) // .WithWindow(w => w.OrderByDesc(g => Agg.Sum(g, x => x.Salary))) // .ToSqlStringAsync(g => new // { // Department = g.Key, // TotalSalary = Agg.Sum(g, x => x.Salary), // Count = Agg.Count(g), // Rank = Win.Rank() // }); //Console.WriteLine(sql); sw.Stop(); var top = ranked.FirstOrDefault(); return Ok("E195", "GroupBy + Window - With Filter", ExampleTier.Pro, sw.ElapsedMilliseconds, ranked.Count, [ $"Filter: Salary > 60k", $"Groups: {ranked.Count}", $"#1: {top?.Department ?? "N/A"} (Total: {top?.TotalSalary:N0})" ]); } } Path: redb/redb.Examples/Examples/E200_SmokeSqlDump.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E200_SmokeSqlDump.cs ---- using System.Diagnostics; using System.Text; using redb.Core; using redb.Core.Query; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Dumps SQL generated for a representative set of LINQ queries that mirror /// the cases in redb.Postgres/sql/v2-pvt/99_smoke_auto.sql. /// Designed so that running it against the Pro provider produces a SQL log /// that can be compared side-by-side with the SQL produced by free v2-pvt /// (pvt_build_query_sql). /// /// The example does not execute any data queries. It only invokes /// for each /// query and writes the resulting SQL to: /// - the console (RAISE-style banner per case); /// - a text file at Output/smoke_sql_dump.txt in the example output /// directory, so it can be diffed with the v2-pvt INSPECT block. /// [ExampleMeta("E200", "SQL dump for smoke cases (Pro vs PVT)", "Query", ExampleTier.Pro, 200, "Sql", "Debug", "Smoke", "Pro", "Pvt", RelatedApis = ["IRedbQueryable.ToSqlStringAsync"])] public class E200_SmokeSqlDump : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var log = new StringBuilder(); int ok = 0, fail = 0; Task EmployeeAsync(string label, Func, IRedbQueryable> build) => DumpAsync(label, () => build(redb.Query()).Take(100)); Task PersonAsync(string label, Func, IRedbQueryable> build) => DumpAsync(label, () => build(redb.Query()).Take(100)); Task CityAsync(string label, Func, IRedbQueryable> build) => DumpAsync(label, () => build(redb.Query()).Take(100)); Task DepartmentAsync(string label, Func, IRedbQueryable> build) => DumpAsync(label, () => build(redb.Query()).Take(100)); async Task DumpAsync(string label, Func> build) where TProps : class, new() { log.AppendLine("-----------------------------------------------------------------"); log.AppendLine($"-- {label}"); log.AppendLine("-----------------------------------------------------------------"); IRedbQueryable? q = null; try { q = build(); } catch (Exception ex) { log.AppendLine($"-- BUILD FAIL: {ex.GetType().Name}: {ex.Message}"); Console.WriteLine($"[BUILD-FAIL] {label}: {ex.Message}"); fail++; log.AppendLine(); return; } try { var sql = await q.ToSqlStringAsync(); log.AppendLine(sql); Console.WriteLine($"[OK] {label}"); ok++; } catch (Exception ex) { log.AppendLine($"-- SQL FAIL: {ex.GetType().Name}: {ex.Message}"); Console.WriteLine($"[FAIL] {label}: {ex.Message}"); fail++; } log.AppendLine(); } // ---------------- Employee: scalar predicates -------------------- await EmployeeAsync("eq string", q => q.Where(e => e.FirstName == "Ivan")); await EmployeeAsync("ne string", q => q.Where(e => e.FirstName != "Ivan")); await EmployeeAsync("in string", q => q.Where(e => new[] { "IT", "HR" }.Contains(e.Department))); await EmployeeAsync("nin string", q => q.Where(e => !new[] { "Sales" }.Contains(e.Department))); await EmployeeAsync("range int", q => q.Where(e => e.Age >= 18 && e.Age <= 65)); await EmployeeAsync("numeric gt decimal", q => q.Where(e => e.Salary > 1000m)); await EmployeeAsync("numeric lt decimal", q => q.Where(e => e.Salary < 1_000_000m)); await EmployeeAsync("numeric range", q => q.Where(e => e.Salary >= 0m && e.Salary <= 1_000_000m)); await EmployeeAsync("null check", q => q.Where(e => e.EmployeeCode == null)); await EmployeeAsync("notNull check", q => q.Where(e => e.EmployeeCode != null)); await EmployeeAsync("startsWith", q => q.Where(e => e.FirstName.StartsWith("A"))); await EmployeeAsync("endsWith", q => q.Where(e => e.LastName.EndsWith("ov"))); await EmployeeAsync("contains", q => q.Where(e => e.Position.Contains("eng"))); await EmployeeAsync("containsIgnoreCase", q => q.Where(e => e.Position.ToLower().Contains("eng"))); await EmployeeAsync("startsWithIgnoreCase", q => q.Where(e => e.FirstName.ToLower().StartsWith("a"))); await EmployeeAsync("endsWithIgnoreCase", q => q.Where(e => e.LastName.ToLower().EndsWith("ov"))); await EmployeeAsync("$and+$or", q => q.Where(e => e.Age > 18 && (e.Department == "IT" || e.Department == "HR"))); await EmployeeAsync("$or top-level", q => q.Where(e => e.Department == "IT" || e.Department == "HR")); await EmployeeAsync("$not", q => q.Where(e => !(e.Age < 18))); await EmployeeAsync("$not + $and", q => q.Where(e => !(e.Age < 18 && e.Department == "IT"))); await EmployeeAsync("multi-field AND merge", q => q.Where(e => e.Department == "IT" && e.Age > 18)); await EmployeeAsync("date gt", q => q.Where(e => e.HireDate > new DateTime(2020, 1, 1))); await EmployeeAsync("date lte", q => q.Where(e => e.HireDate <= new DateTime(2030, 1, 1))); await EmployeeAsync("date range", q => q.Where(e => e.HireDate >= new DateTime(2000, 1, 1) && e.HireDate < new DateTime(2030, 1, 1))); // ---------------- Employee: base-field pushdown (WhereRedb) ------ await EmployeeAsync("base _id gt", q => q.WhereRedb(o => o.Id > 0)); await EmployeeAsync("base 0$:Name startsWith", q => q.WhereRedb(o => o.Name.StartsWith("E"))); await EmployeeAsync("pushdown _date_create gte",q => q.WhereRedb(o => o.DateCreate >= new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero))); await EmployeeAsync("pushdown base+props AND", q => q.WhereRedb(o => o.Id > 0).Where(e => e.FirstName.StartsWith("A"))); await EmployeeAsync("pushdown $or all-base", q => q.WhereRedb(o => o.Id < 10 || o.Id > 100)); await EmployeeAsync("pushdown $not base", q => q.WhereRedb(o => !(o.Id < 0))); await EmployeeAsync("pushdown nested $and+$or", q => q.WhereRedb(o => o.Id > 0).Where(e => e.Department == "IT" || e.Department == "HR")); // ---------------- Employee: expression engine (B2) --------------- await EmployeeAsync("expr arithmetic gt", q => q.Where(e => e.Age + 1 > 18)); await EmployeeAsync("expr mul base pushdown", q => q.WhereRedb(o => o.Id * 2 < 1_000_000)); await EmployeeAsync("expr upper eq", q => q.Where(e => e.FirstName.ToUpper() == "IVAN")); await EmployeeAsync("expr concat ilike", q => q.Where(e => (e.FirstName + " " + e.LastName).ToLower().Contains("van"))); await EmployeeAsync("expr coalesce eq", q => q.Where(e => (e.EmployeeCode ?? "none") == "IT")); await EmployeeAsync("expr length gt", q => q.Where(e => e.FirstName.Length > 0)); await EmployeeAsync("expr abs sub", q => q.Where(e => Math.Abs(e.Age - 30) < 1000)); await EmployeeAsync("expr salary * 12", q => q.Where(e => e.Salary * 12m > 1_000_000m)); // ---------------- Employee: arrays ------------------------------- await EmployeeAsync("array contains", q => q.Where(e => e.Skills!.Contains("C#"))); await EmployeeAsync("array length gt", q => q.Where(e => e.Skills!.Length > 0)); await EmployeeAsync("array length eq 3", q => q.Where(e => e.Skills!.Length == 3)); await EmployeeAsync("array any", q => q.Where(e => e.Skills!.Any())); await EmployeeAsync("array not any", q => q.Where(e => !e.Skills!.Any())); await EmployeeAsync("array int contains 5", q => q.Where(e => e.SkillLevels!.Contains(5))); // ---------------- Employee: dictionaries ------------------------- await EmployeeAsync("dict ContainsKey work", q => q.Where(e => e.PhoneDirectory!.ContainsKey("work"))); await EmployeeAsync("dict indexer eq", q => q.Where(e => e.PhoneDirectory!["work"] == "+7-000-0000000")); await EmployeeAsync("dict nested .City", q => q.Where(e => e.OfficeLocations!["Moscow"].City == "Moscow")); await EmployeeAsync("dict nested .Street!=null",q => q.Where(e => e.OfficeLocations!["Moscow"].Street != null)); // ---------------- Person: ListItem accessors --------------------- await PersonAsync("Person eq Name", q => q.Where(p => p.Name == "Alice")); await PersonAsync("Person Age range", q => q.Where(p => p.Age >= 18 && p.Age <= 99)); await PersonAsync("Person Email contains @", q => q.Where(p => p.Email.Contains("@"))); await PersonAsync("Person Status.Value eq", q => q.Where(p => p.Status!.Value == "Active")); await PersonAsync("Person Roles[].Value any", q => q.Where(p => p.Roles!.Any(r => r.Value == "admin"))); // ---------------- City ------------------------------------------- await CityAsync("City bool true", q => q.Where(c => c.IsCapital == true)); await CityAsync("City bool false", q => q.Where(c => c.IsCapital == false)); await CityAsync("City coords length eq 2", q => q.Where(c => c.Coordinates.Length == 2)); await CityAsync("City population gt", q => q.Where(c => c.Population > 1000)); await CityAsync("City region startsWith M", q => q.Where(c => c.Region.StartsWith("M"))); await CityAsync("City name in", q => q.Where(c => new[] { "Moscow", "Paris" }.Contains(c.Name))); // ---------------- Department ------------------------------------- await DepartmentAsync("Dept eq bool", q => q.Where(d => d.IsActive == true)); await DepartmentAsync("Dept name startsWith", q => q.Where(d => d.Name.StartsWith("IT"))); await DepartmentAsync("Dept code contains '-'", q => q.Where(d => d.Code.Contains("-"))); await DepartmentAsync("Dept budget >= 0", q => q.Where(d => d.Budget >= 0m)); await DepartmentAsync("Dept description != null", q => q.Where(d => d.Description != null)); // ---------------- Write SQL log to disk -------------------------- string? outPath = null; try { var dir = Path.Combine(AppContext.BaseDirectory, "Output"); Directory.CreateDirectory(dir); outPath = Path.Combine(dir, "smoke_sql_dump.txt"); await File.WriteAllTextAsync(outPath, log.ToString()); } catch (Exception ex) { Console.WriteLine($"[WARN] failed to write dump file: {ex.Message}"); } sw.Stop(); return Ok("E200", "SQL dump for smoke cases (Pro vs PVT)", ExampleTier.Pro, sw.ElapsedMilliseconds, ok + fail, new[] { $"Cases dumped: {ok} OK, {fail} FAIL", outPath != null ? $"Output: {outPath}" : "Output file: ", "Compare with: redb.Postgres/sql/v2-pvt/99_smoke_auto.sql (INSPECT block)" }); } } Path: redb/redb.Examples/Examples/E201_NullCheckBaseIdAmbiguity.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E201_NullCheckBaseIdAmbiguity.cs ---- using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using redb.Core; using redb.Core.Query; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Reproduces the ambiguous _id defect in the PVT CTE. /// /// A props filter == null switches the PVT CTE into the two-table form /// (FROM _objects o_src LEFT JOIN _values v), while the base-field filter /// is compiled without a table alias. _id is the only column present in /// BOTH _objects and _values, so the combination produces /// column reference "_id" is ambiguous. /// /// Four cases: two controls that must stay green, the repro, and a control that /// pins the diagnosis to _id specifically (_id_parent exists only /// in _objects, so it must stay green even in the two-table form). /// /// Scope: verified against redb.Postgres.Pro. MSSql.Pro and SQLite.Pro generate /// the same shape but are out of scope for now. /// [ExampleMeta("E201", "NullCheck + base Id: ambiguous _id in PVT CTE", "Query", ExampleTier.Pro, 200, "Sql", "Debug", "Bug", "Pro", "Pvt", "NullCheck", RelatedApis = ["IRedbQueryable.ToSqlStringAsync", "IRedbQueryable.WhereRedb"])] public class E201_NullCheckBaseIdAmbiguity : ExampleBase { /// Bare _id: not preceded by a dot or word char, not followed by a word char. private static readonly Regex BareId = new(@"(? RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var log = new StringBuilder(); var summary = new List(); var suspects = 0; async Task CaseAsync(string label, string expectation, IRedbQueryable query) { log.AppendLine("-----------------------------------------------------------------"); log.AppendLine($"-- {label}"); log.AppendLine($"-- expected: {expectation}"); log.AppendLine("-----------------------------------------------------------------"); string sql; try { sql = await query.ToSqlStringAsync(); } catch (Exception ex) { log.AppendLine($"-- SQL BUILD FAIL: {ex.GetType().Name}: {ex.Message}"); log.AppendLine(); summary.Add($"{label}: SQL build failed ({ex.GetType().Name})"); Console.WriteLine($"[BUILD-FAIL] {label}: {ex.Message}"); return; } log.AppendLine(sql); log.AppendLine(); // Console.WriteLine(); // Console.WriteLine($"--- {label} (expected: {expectation}) ---"); // Console.WriteLine(sql); // Static verdict: the two-table CTE form together with an unqualified _id. var twoTableForm = sql.Contains("FROM _objects o_src"); var hasBareId = BareId.IsMatch(sql); var verdict = twoTableForm && hasBareId ? "AMBIGUOUS" : "clean"; if (verdict == "AMBIGUOUS") suspects++; // Dynamic verdict: does the database actually accept it. string execVerdict; try { var rows = await query.ToListAsync(); execVerdict = $"executed, {rows.Count} rows"; } catch (Exception ex) { execVerdict = $"{ex.GetType().Name}: {ex.Message.Split('\n')[0]}"; } log.AppendLine($"-- static: two-table form={twoTableForm}, bare _id={hasBareId} => {verdict}"); log.AppendLine($"-- runtime: {execVerdict}"); log.AppendLine(); summary.Add($"{label}: {verdict} | {execVerdict}"); Console.WriteLine($"[{verdict,9}] {label} -> {execVerdict}"); } // 1. Control. Props == null alone: two-table form, but no base filter, so nothing to qualify. await CaseAsync( "control: props == null only", "clean", redb.Query() .Where(e => e.EmployeeCode == null) .Take(10)); // 2. Control. Base Id alone: single-table subquery over _objects, name resolves in its own scope. await CaseAsync( "control: base Id only", "clean", redb.Query() .WhereRedb(o => o.Id > 0) .Where(e => e.Age > 0) .Take(10)); // 3. Repro. Both at once. await CaseAsync( "repro: props == null + base Id", "AMBIGUOUS", redb.Query() .Where(e => e.EmployeeCode == null) .WhereRedb(o => o.Id > 0) .Take(10)); // 4. Control. Same shape, but the base column exists only in _objects. // Proves the defect is specific to _id and not to base-field pushdown in general. await CaseAsync( "control: props == null + base ParentId", "clean", redb.Query() .Where(e => e.EmployeeCode == null) .WhereRedb(o => o.ParentId != null) .Take(10)); string? outPath = null; try { var dir = Path.Combine(AppContext.BaseDirectory, "Output"); Directory.CreateDirectory(dir); outPath = Path.Combine(dir, "nullcheck_baseid_ambiguity.txt"); await File.WriteAllTextAsync(outPath, log.ToString()); } catch (Exception ex) { Console.WriteLine($"[WARN] failed to write dump file: {ex.Message}"); } sw.Stop(); // The run time above is the sum over all the queries of the example, each printed and then // executed, so the count comes first: without it the figure reads as one slow query. var output = new List { $"{summary.Count} queries in this example: SQL printed, then each executed" }; output.AddRange(summary); output.AddRange(new[] { $"Suspect cases: {suspects} (expected 1: the repro)", outPath != null ? $"Output: {outPath}" : "Output file: " }); return Ok("E201", "NullCheck + base Id: ambiguous _id in PVT CTE", ExampleTier.Pro, sw.ElapsedMilliseconds, summary.Count, output.ToArray()); } } Path: redb/redb.Examples/Examples/E202_PvtPrefilter.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E202_PvtPrefilter.cs ---- using System.Diagnostics; using System.Text; using redb.Core; using redb.Core.Query; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Dumps SQL for the cases the PVT prefilter is meant to handle, so the same run can be /// compared with and without the cutting step. /// /// The prefilter is opt-in. Run twice and diff: /// dotnet run --project redb.Examples -- E202 (off) /// REDB_PVT_PREFILTER=1 dotnet run --project redb.Examples -- E202 (on) /// /// Each case also executes, and the example compares the returned id sets between the two /// runs by writing them to the dump. The prefilter is a superset by construction, so the id /// sets MUST be identical. A difference is a defect, not a tuning question. /// /// Expected shapes when enabled: /// top-level OR -> disjunction spliced into the _values scan (Row form) /// top-level AND -> Row form too, when the single branch covers the whole pivot /// unanalysable -> no prefilter at all, SQL identical to the disabled run /// [ExampleMeta("E202", "PVT prefilter: SQL with and without the cutting step", "Query", ExampleTier.Pro, 200, "Sql", "Debug", "Prefilter", "Pro", "Pvt", RelatedApis = ["IRedbQueryable.ToSqlStringAsync"])] public class E202_PvtPrefilter : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // What the service actually runs with: Program.cs may set it without the environment variable. var enabled = redb.Configuration.EnablePvtPrefilter; var log = new StringBuilder(); var summary = new List(); var withPrefilter = 0; log.AppendLine($"-- EnablePvtPrefilter = {(enabled ? "true (enabled)" : "false (disabled)")}"); log.AppendLine(); async Task CaseAsync(string label, string expectation, IRedbQueryable query) { log.AppendLine("-----------------------------------------------------------------"); log.AppendLine($"-- {label}"); log.AppendLine($"-- expected when enabled: {expectation}"); log.AppendLine("-----------------------------------------------------------------"); string sql; try { sql = await query.ToSqlStringAsync(); } catch (Exception ex) { log.AppendLine($"-- SQL BUILD FAIL: {ex.GetType().Name}: {ex.Message}"); log.AppendLine(); summary.Add($"{label}: SQL build failed"); Console.WriteLine($"[BUILD-FAIL] {label}: {ex.Message}"); return; } log.AppendLine(sql); // Console.WriteLine(); // Console.WriteLine($"--- {label} (expected when enabled: {expectation}) ---"); // Console.WriteLine(sql); // "pf" is the alias the planner gives the prefilter scan. The Row form is the extra // parenthesised group spliced into the _values scan; note it may hold a SINGLE branch // (a merged range), so matching on " OR " would miss it. // Semi form was removed after measuring 3x worse than nothing; this stays as a tripwire. var hasSemi = sql.Contains("FROM _values pf"); var hasRow = sql.Contains("AND ((v._id_structure"); var form = hasSemi ? "Semi" : hasRow ? "Row" : "none"; if (form != "none") withPrefilter++; string ids; try { var rows = await query.ToListAsync(); ids = rows.Count == 0 ? "" : string.Join(",", rows.Select(r => r.Id).OrderBy(x => x)); } catch (Exception ex) { ids = $"EXEC FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}"; } log.AppendLine($"-- prefilter form: {form}"); log.AppendLine($"-- ids: {ids}"); log.AppendLine(); summary.Add($"{label}: {form}"); Console.WriteLine($"[{form,4}] {label}"); } // Top-level OR, both branches selective. A production case: one search string, several // fields. Row form, and with pg_trgm the LIKE finally reaches the column. await CaseAsync( "OR: two string fields, same needle", "Row", redb.Query() .Where(e => e.Position.Contains("Design") || e.Department.Contains("Design")) .Take(100)); // Top-level AND on a single field: two predicates merge into one selective range. // Splitting them into an OR would give a tautology, hence the merge. await CaseAsync( "AND: range on one field", "Row, single branch with both bounds merged", redb.Query() .Where(e => e.Salary >= 60000m && e.Salary < 90000m) .Take(100)); // Top-level AND across fields. Only the most selective conjunct is pushed; the weak // one (Position != "") stays above the aggregate where it belongs. await CaseAsync( "AND: three fields, one selective", "none (pivot not covered: Position and Age have no branch)", redb.Query() .Where(e => e.Position != "" && e.Age >= 30 && e.Salary > 70000m) .Take(100)); // One weak branch in an OR voids the group: a disjunction is never narrower than its // widest term, so the extra scan would buy nothing. await CaseAsync( "OR: one weak branch", "none (weakest branch below threshold)", redb.Query() .Where(e => e.Position != "" || e.Salary > 70000m) .Take(100)); // Null check is not expressible as a row predicate. Under AND it is simply dropped // and the other conjunct still gets pushed. await CaseAsync( "AND: null check plus selective field", "none (pivot not covered: EmployeeCode has no branch)", redb.Query() .Where(e => e.EmployeeCode == null && e.Salary > 70000m) .Take(100)); // Arrays are not single-row values. Under OR that voids the whole prefilter. await CaseAsync( "OR: array branch", "none (array is not a row predicate)", redb.Query() .Where(e => e.Skills!.Contains("C#") || e.Salary > 70000m) .Take(100)); // Sorting pulls Age into the pivot without putting it in the filter. The Row form // would null that column out, so the guard suppresses the prefilter entirely. // // ThenByRedb(Id) is not decoration: Age has thousands of ties, and Take(100) over a tie // returns whichever hundred the plan happens to produce. Without a unique tiebreak this // case reported a difference between two runs of the SAME configuration, which reads as // a prefilter defect and is not one. Id is a base field, so it adds nothing to the pivot // and the guard still fires on Age. await CaseAsync( "OR plus OrderBy on an uncovered field", "none (pivot coverage guard: Age comes from OrderBy)", redb.Query() .Where(e => e.Position.Contains("Design") || e.Department.Contains("Design")) .OrderBy(e => e.Age) .ThenByRedb(o => o.Id) .Take(100)); // ---- dates ------------------------------------------------------- // Same algebra as numbers, different column (_datetimeoffset) and a different // parameter round-trip. Worth its own cases: a DateTime that survives C# to Npgsql // to the pivot but not into the prefilter branch would silently narrow the result. // Closed range on one field. Two predicates, one structure, one merged branch. await CaseAsync( "AND: date range on one field", "Row, single branch with both bounds merged", redb.Query() .Where(e => e.HireDate >= new DateTime(2030, 1, 1) && e.HireDate < new DateTime(2031, 1, 1)) .Take(100)); // Open-ended comparison, single leaf at the root. await CaseAsync( "date: single greater-than", "Row, one branch", redb.Query() .Where(e => e.HireDate > new DateTime(2048, 1, 1)) .Take(100)); // Mixed types under OR: a date branch and a string branch in one disjunction. await CaseAsync( "OR: date branch plus string branch", "Row, two branches on different columns", redb.Query() .Where(e => e.HireDate > new DateTime(2050, 1, 1) || e.Position.Contains("Design")) .Take(100)); // Inequality on a date is not selective enough to earn a scan. await CaseAsync( "date: not-equal", "none (NotEqual passes almost everything)", redb.Query() .Where(e => e.HireDate != new DateTime(2030, 1, 1)) .Take(100)); string? outPath = null; try { var dir = Path.Combine(AppContext.BaseDirectory, "Output"); Directory.CreateDirectory(dir); outPath = Path.Combine(dir, enabled ? "pvt_prefilter_on.txt" : "pvt_prefilter_off.txt"); await File.WriteAllTextAsync(outPath, log.ToString()); } catch (Exception ex) { Console.WriteLine($"[WARN] failed to write dump file: {ex.Message}"); } sw.Stop(); // The run time above is the sum over all the queries of the example, each printed and then // executed, so the count comes first: without it the figure reads as one slow query. var output = new List { $"{summary.Count} queries in this example: SQL printed, then each executed", $"Prefilter: {(enabled ? "ENABLED" : "disabled")}, applied in {withPrefilter} of {summary.Count} cases" }; output.AddRange(summary); output.AddRange(new[] { outPath != null ? $"Output: {outPath}" : "Output file: ", "Diff pvt_prefilter_off.txt against pvt_prefilter_on.txt: id sets must match exactly" }); return Ok("E202", "PVT prefilter: SQL with and without the cutting step", ExampleTier.Pro, sw.ElapsedMilliseconds, summary.Count, output.ToArray()); } } Path: redb/redb.Examples/Examples/E203_SeedVolume.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E203_SeedVolume.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Examples.Models; using redb.Examples.Output; using redb.MSSql.Data; using redb.Postgres.Data; using redb.SQLite.Data; namespace redb.Examples.Examples; /// /// Seeds a large company: Employee objects arranged as a reporting tree. /// /// Every employee but the first reports to a manager, and every manager has /// direct reports, so 100000 employees form a tree six levels deep. /// The same objects answer both kinds of query: /// /// /// redb.Query<EmployeeProps>().Where(e => e.Salary > 90000) // everyone /// redb.TreeQuery<EmployeeProps>(managerId).Where(e => e.Salary > 90000) // one manager's people /// /// /// /// dotnet run --project redb.Examples -- E203 /// REDB_SEED_COUNT=20000 dotnet run --project redb.Examples -- E203 /// /// /// The whole-suite sweep never seeds. Seeding runs only when the example is NAMED on the /// command line (default 100000 employees). REDB_SEED_COUNT overrides the size (0 disables even an /// explicit run), REDB_SEED_BATCH the batch (default 1000). /// /// Objects have the shape E000 builds: about 60 _values rows each, with arrays, nested classes /// and dictionaries, so 100000 employees land around 6M rows in _values. /// /// This example WRITES a lot. It appends and never clears: every run adds one more company with /// its own head, so running it twice doubles the data. It ends by refreshing planner statistics /// through redb.Maintenance.AnalyzeAsync(); after a bulk load the planner's estimates are /// stale until that is done. /// [ExampleMeta("E203", "Seed volume: employees as a reporting tree", "Setup", ExampleTier.Pro, 200, "Setup", "BulkInsert", "Tree", "Benchmark", RelatedApis = ["IRedbService.AddNewObjectsAsync", "IRedbContext.NextObjectIdBatchAsync"])] public class E203_SeedVolume : ExampleBase { /// How many people report to one manager. private const int DirectReports = 10; public override async Task RunAsync(IRedbService redb) { // Seeding volume is a decision, not a side effect. Being NAMED on the command line is // that decision; being reached by the whole-suite sweep is not - the sweep always skips. var isExplicitRun = ExplicitlyRequestedIds?.Contains("E203") == true; var total = ReadInt("REDB_SEED_COUNT", isExplicitRun ? 100_000 : 0); var batchSize = ReadInt("REDB_SEED_BATCH", 1_000); if (total == 0) { return Ok("E203", "Seed volume: employees as a reporting tree", ExampleTier.Pro, 0, [ "Skipped: the whole-suite sweep never seeds.", "To seed: dotnet run --project redb.Examples -- E203 (default 100000)", "REDB_SEED_COUNT overrides the size, REDB_SEED_BATCH the batch (default 1000).", "100000 employees land around 6M rows in _values and take ~20 minutes.", "It appends and never clears, so running it twice doubles the data." ]) with { Skipped = true }; } if (total < 0 || batchSize <= 0) return Fail("E203", "Seed volume: employees as a reporting tree", ExampleTier.Pro, 0, "REDB_SEED_COUNT must not be negative and REDB_SEED_BATCH must be positive"); // Continue numbering after whatever is already there, so names and codes stay unique // across runs. var existing = await redb.Query().CountAsync(); Console.WriteLine(); Console.WriteLine($"Seeding {total:N0} employees in batches of {batchSize:N0}, {DirectReports} direct reports per manager"); Console.WriteLine($"Already in scheme: {existing:N0}. New objects start at index {existing:N0}."); Console.WriteLine($"Expect roughly {total * 60L:N0} rows in _values. This appends, it never clears."); Console.WriteLine(); var sw = Stopwatch.StartNew(); // All ids up front: a manager's id has to be known before the reports are created. var ids = await redb.Context.NextObjectIdBatchAsync(total); var batchTimer = new Stopwatch(); var seeded = 0; var batches = 0; // Bulk-load mode: the plain secondary indexes of _values and _objects go before the load and are // rebuilt after it, over the whole tables. Keys stay: primary keys, unique indexes and the foreign // keys resting on them check every row as usual. Dropping and rebuilding are inside the measured time. var droppedIndexes = await SetAsidePlainIndexesAsync(redb); var rebuildTimer = new Stopwatch(); try { while (seeded < total) { var take = Math.Min(batchSize, total - seeded); batchTimer.Restart(); var employees = E000_BulkInsert.CreateEmployees(take, existing + seeded); for (var i = 0; i < employees.Count; i++) { // Position n reports to position (n - 1) / DirectReports; position 0 heads the // company. A manager always comes earlier than the reports, so it is already saved // or sits in the same batch. var position = seeded + i; employees[i].id = ids[position]; employees[i].parent_id = position == 0 ? null : ids[(position - 1) / DirectReports]; } await redb.AddNewObjectsAsync(employees.Cast>().ToList()); batchTimer.Stop(); seeded += employees.Count; batches++; var pct = seeded * 100.0 / total; var overallRate = seeded * 1000.0 / Math.Max(sw.ElapsedMilliseconds, 1); var remaining = overallRate > 0 ? TimeSpan.FromSeconds((total - seeded) / overallRate) : TimeSpan.Zero; Console.WriteLine( $"[{seeded,8:N0}/{total:N0}] {pct,5:F1}% " + $"batch {batchTimer.ElapsedMilliseconds,6:N0} ms " + $"avg {overallRate,7:F0} obj/s " + $"elapsed {sw.Elapsed:hh\\:mm\\:ss} " + $"ETA {remaining:hh\\:mm\\:ss}"); } } finally { // Also after a failed batch: a database left without its indexes would slow every later query. rebuildTimer.Start(); await RestoreIndexesAsync(redb, droppedIndexes); rebuildTimer.Stop(); } sw.Stop(); var finalCount = await redb.Query().CountAsync(); var rate = seeded * 1000.0 / Math.Max(sw.ElapsedMilliseconds, 1); // A bulk load leaves the planner's statistics behind reality. The Maintenance facade runs // the provider's own refresh (ANALYZE / sp_updatestats / PRAGMA analysis_limit + ANALYZE), // so the seed hands back a database that is ready to be queried and measured. Console.WriteLine(); Console.WriteLine("Refreshing planner statistics (redb.Maintenance.AnalyzeAsync)..."); var analyzeSw = Stopwatch.StartNew(); await redb.Maintenance.AnalyzeAsync(); analyzeSw.Stop(); Console.WriteLine(); var levels = 1; for (long reach = 1, width = 1; reach < total; levels++) { width *= DirectReports; reach += width; } return Ok("E203", "Seed volume: employees as a reporting tree", ExampleTier.Pro, sw.ElapsedMilliseconds, seeded, [ $"Seeded {seeded:N0} in {batches:N0} batches of {batchSize:N0}", $"Rate: {rate:F0} obj/sec | scheme now holds {finalCount:N0} employees", $"Reporting tree: {levels} levels, head of the company id {ids[0]}", $"Try: redb.TreeQuery({ids[0]}) and redb.Query()", $"Planner statistics refreshed: Maintenance.AnalyzeAsync in {analyzeSw.ElapsedMilliseconds:N0} ms", droppedIndexes.Count == 0 ? "Bulk-load mode: off (no plain indexes set aside)" : $"Bulk-load mode: {droppedIndexes.Count} plain indexes set aside and rebuilt in {rebuildTimer.ElapsedMilliseconds:N0} ms (inside the measured time)" ]); } /// /// Takes the plain secondary indexes of _values and _objects out of the load: neither unique /// nor backing a constraint, so no key and no foreign key depends on them. Returns the statements that /// bring them back. PostgreSQL and SQLite drop them and keep their definitions; SQL Server disables them /// and rebuilds them later from its own catalog. /// private static async Task> SetAsidePlainIndexesAsync(IRedbService redb) => redb.Context switch { NpgsqlRedbContext => await DropPostgresIndexesAsync(redb), SqlRedbContext => await DisableSqlServerIndexesAsync(redb), SqliteRedbContext => await DropSqliteIndexesAsync(redb), _ => [] }; private static async Task> DropPostgresIndexesAsync(IRedbService redb) { const string plainIndexes = """ FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace WHERE n.nspname = current_schema() AND t.relname IN ('_values', '_objects') AND NOT x.indisunique AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = x.indexrelid) """; var definitions = await redb.Context.QueryScalarListAsync( $"SELECT pg_get_indexdef(x.indexrelid) {plainIndexes} ORDER BY i.relname"); var names = await redb.Context.QueryScalarListAsync( $"SELECT format('%I', i.relname) {plainIndexes} ORDER BY i.relname"); Console.WriteLine($"Bulk-load mode: dropping {names.Count} plain indexes of _values and _objects (keys stay)."); foreach (var name in names) await redb.Context.ExecuteAsync($"DROP INDEX IF EXISTS {name}"); return definitions; } /// /// Disables the plain nonclustered indexes: a disabled index is not maintained by inserts, and /// ALTER INDEX ... REBUILD brings it back from the catalog. The clustered index stays, a table /// without it cannot be read or written. /// private static async Task> DisableSqlServerIndexesAsync(IRedbService redb) { var targets = await redb.Context.QueryScalarListAsync(""" SELECT QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) FROM sys.indexes i JOIN sys.tables t ON t.object_id = i.object_id JOIN sys.schemas s ON s.schema_id = t.schema_id WHERE s.name = SCHEMA_NAME() AND t.name IN ('_values', '_objects') AND i.type = 2 AND i.is_unique = 0 AND i.is_primary_key = 0 AND i.is_unique_constraint = 0 AND i.is_disabled = 0 ORDER BY i.name """); Console.WriteLine($"Bulk-load mode: disabling {targets.Count} plain indexes of _values and _objects (keys stay)."); foreach (var target in targets) await redb.Context.ExecuteAsync($"ALTER INDEX {target} DISABLE"); return targets.Select(target => $"ALTER INDEX {target} REBUILD").ToList(); } /// /// Drops the plain indexes: those with a CREATE statement in sqlite_master (the indexes SQLite /// makes itself for keys have none) that are not unique. Their statements are kept for the rebuild. /// private static async Task> DropSqliteIndexesAsync(IRedbService redb) { const string plainIndexes = """ FROM sqlite_master WHERE type = 'index' AND tbl_name IN ('_values', '_objects') AND sql IS NOT NULL AND upper(sql) NOT LIKE 'CREATE UNIQUE%' """; var definitions = await redb.Context.QueryScalarListAsync($"SELECT sql {plainIndexes} ORDER BY name"); var names = await redb.Context.QueryScalarListAsync( $"SELECT '\"' || replace(name, '\"', '\"\"') || '\"' {plainIndexes} ORDER BY name"); Console.WriteLine($"Bulk-load mode: dropping {names.Count} plain indexes of _values and _objects (keys stay)."); foreach (var name in names) await redb.Context.ExecuteAsync($"DROP INDEX IF EXISTS {name}"); return definitions; } /// Brings back the indexes set aside by , over the whole tables. private static async Task RestoreIndexesAsync(IRedbService redb, List restoreStatements) { if (restoreStatements.Count == 0) return; Console.WriteLine(); Console.WriteLine($"Bulk-load mode: rebuilding {restoreStatements.Count} indexes..."); var sw = Stopwatch.StartNew(); foreach (var statement in restoreStatements) await redb.Context.ExecuteAsync(statement); sw.Stop(); Console.WriteLine($"Bulk-load mode: indexes rebuilt in {sw.ElapsedMilliseconds:N0} ms"); } private static int ReadInt(string name, int fallback) { var raw = Environment.GetEnvironmentVariable(name); return int.TryParse(raw, out var parsed) ? parsed : fallback; } } Path: redb/redb.Examples/Examples/E204_TreePrefilter.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E204_TreePrefilter.cs ---- using System.Diagnostics; using System.Text; using redb.Core; using redb.Core.Query; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Tree counterpart of E202: dumps the SQL a tree query generates with and without the PVT /// prefilter, and checks that the row count is unchanged. /// /// /// dotnet run --project redb.Examples -- E204 (off) /// REDB_PVT_PREFILTER=1 dotnet run --project redb.Examples -- E204 (on) /// /// /// A subtree already bounds the work, unlike a flat query which always scans the whole scheme, /// so the prefilter only starts paying once the subtree itself is large. Measured on a 6-level /// tree of 99200 nodes: 1189 -> 401 ms and 716677 -> 333755 buffers, identical result sets. /// /// Needs a tree with real depth under the Employee scheme: E203 seeds one, employees arranged as a /// reporting tree with ten direct reports per manager. Without depth this example still runs, it /// just measures very little. /// /// The differential check here is by COUNT rather than by id set: a tree query over a large /// subtree returns tens of thousands of objects and materialising them all would dwarf the /// query being measured. Full id-set equality was verified separately in psql. /// [ExampleMeta("E204", "PVT prefilter in tree queries", "Trees", ExampleTier.Pro, 200, "Sql", "Debug", "Prefilter", "Pro", "Pvt", "Tree", RelatedApis = ["IRedbService.TreeQuery", "IRedbQueryable.ToSqlStringAsync"])] public class E204_TreePrefilter : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // What the service actually runs with: Program.cs may set it without the environment variable. var enabled = redb.Configuration.EnablePvtPrefilter; var root = await redb.TreeQuery().WhereRoots().FirstOrDefaultAsync(); if (root == null) { sw.Stop(); return Fail("E204", "PVT prefilter in tree queries", ExampleTier.Pro, sw.ElapsedMilliseconds, "No Employee tree found. Seed one with E203."); } var log = new StringBuilder(); var summary = new List(); var withPrefilter = 0; log.AppendLine($"-- EnablePvtPrefilter = {(enabled ? "true (enabled)" : "false (disabled)")}"); log.AppendLine($"-- root id = {root.Id}"); log.AppendLine(); async Task CaseAsync(string label, string expectation, IRedbQueryable query) { log.AppendLine("-----------------------------------------------------------------"); log.AppendLine($"-- {label}"); log.AppendLine($"-- expected when enabled: {expectation}"); log.AppendLine("-----------------------------------------------------------------"); string sql; try { sql = await query.ToSqlStringAsync(); } catch (Exception ex) { log.AppendLine($"-- SQL BUILD FAIL: {ex.GetType().Name}: {ex.Message}"); log.AppendLine(); summary.Add($"{label}: SQL build failed"); Console.WriteLine($"[BUILD-FAIL] {label}: {ex.Message}"); return; } log.AppendLine(sql); // Console.WriteLine(); // Console.WriteLine($"--- {label} (expected when enabled: {expectation}) ---"); // Console.WriteLine(sql); var hasRow = sql.Contains("AND ((v._id_structure"); // Dropping _objects oo is the second half of the change and only fires together // with the prefilter; surfacing it separately makes a half-applied change visible. var droppedObjects = sql.Contains("FROM tree t\n") || sql.Contains(" FROM tree t"); var form = hasRow ? (droppedObjects ? "Row+" : "Row") : "none"; if (hasRow) withPrefilter++; string count; var timer = Stopwatch.StartNew(); try { count = (await query.CountAsync()).ToString(); } catch (Exception ex) { count = $"EXEC FAIL {ex.GetType().Name}: {ex.Message.Split('\n')[0]}"; } timer.Stop(); log.AppendLine($"-- prefilter form: {form}"); log.AppendLine($"-- count: {count} in {timer.ElapsedMilliseconds} ms"); log.AppendLine(); summary.Add($"{label}: {form}, count={count}"); Console.WriteLine($"[{form,5}] {label} -> count={count} in {timer.ElapsedMilliseconds} ms"); } // The text-search shape: one needle across two string fields. Row form plus the dropped // _objects join, and pg_trgm finally reaches the column. await CaseAsync( "OR: two string fields, same needle", "Row+ (prefilter and _objects join dropped)", redb.TreeQuery(root.Id) .Where(e => e.Position.Contains("Design") || e.Department.Contains("Design"))); // Two predicates on one field merge into a single selective branch. await CaseAsync( "AND: range on one field", "Row+ (both bounds merged)", redb.TreeQuery(root.Id) .Where(e => e.Salary >= 60000m && e.Salary < 90000m)); // Dates use _datetimeoffset and a different parameter round-trip. await CaseAsync( "AND: date range", "Row+", redb.TreeQuery(root.Id) .Where(e => e.HireDate >= new DateTime(2030, 1, 1) && e.HireDate < new DateTime(2031, 1, 1))); // Pivot not covered: Position and Age have no branch of their own, so the guard suppresses // the prefilter rather than nulling their columns out. await CaseAsync( "AND: three fields, one selective", "none (pivot not covered)", redb.TreeQuery(root.Id) .Where(e => e.Position != "" && e.Age >= 30 && e.Salary > 70000m)); // Null check switches the CTE to the LEFT JOIN form, where dropping rows would blur // "absent" and "present but not matching". await CaseAsync( "AND: null check plus selective field", "none (hasNullCheck)", redb.TreeQuery(root.Id) .Where(e => e.EmployeeCode == null && e.Salary > 70000m)); string? outPath = null; try { var dir = Path.Combine(AppContext.BaseDirectory, "Output"); Directory.CreateDirectory(dir); outPath = Path.Combine(dir, enabled ? "tree_prefilter_on.txt" : "tree_prefilter_off.txt"); await File.WriteAllTextAsync(outPath, log.ToString()); } catch (Exception ex) { Console.WriteLine($"[WARN] failed to write dump file: {ex.Message}"); } sw.Stop(); // The run time above is the sum over all the queries of the example, each a count over the // whole subtree of the root, so the count of queries comes first: without it the figure reads // as one slow query. var output = new List { $"{summary.Count} queries in this example: SQL printed, then each counted over the subtree of root {root.Id}", $"Prefilter: {(enabled ? "ENABLED" : "disabled")}, applied in {withPrefilter} of {summary.Count} cases" }; output.AddRange(summary); output.AddRange(new[] { outPath != null ? $"Output: {outPath}" : "Output file: ", "Diff tree_prefilter_off.txt against tree_prefilter_on.txt: counts must match exactly" }); return Ok("E204", "PVT prefilter in tree queries", ExampleTier.Pro, sw.ElapsedMilliseconds, summary.Count, output.ToArray()); } } Path: redb/redb.Examples/Examples/E205_WhereRedbSystemFields.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E205_WhereRedbSystemFields.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// WhereRedb: filtering on SYSTEM fields of _objects (id, parent_id, key, value_string, /// date_modify and friends) as opposed to Where, which filters on your Props. The two /// compose freely in one query - the system predicate and the Props predicate both run /// server-side. Patterns shown here mirror production usage: a lookup by the service /// value_string key, an id-set prefilter with Contains, and the composite /// WhereRedb().Where() shape (discussion #12, item on WhereRedb docs). /// [ExampleMeta("E205", "WhereRedb - System Fields and Composition", "Query", ExampleTier.Free, 1, "WhereRedb", "Query", "SystemFields", "Composite", RelatedApis = ["IRedbQueryable.WhereRedb", "IRedbQueryable.Where", "IRedbObject.Key", "IRedbObject.ValueString"])] public class E205_WhereRedbSystemFields : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Seed: three employees carrying SYSTEM fields alongside Props. The service fields // (key, value_string, value_long...) live on the _objects row itself - no scheme // change needed - and are ideal for lookup keys next to your business data. var seeded = new List(); for (var i = 0; i < 3; i++) { var employee = new RedbObject { name = $"e205-employee-{i}", key = 7000 + i, // numeric service key value_string = i == 0 ? "e205:head-of-desk" : null, // string lookup key Props = new EmployeeProps { FirstName = $"E205-{i}", LastName = "Sample", Department = i == 2 ? "Sales" : "IT", Salary = 50000m + i * 10000m, }, }; seeded.Add(await redb.SaveAsync(employee)); } // 1. Lookup by the service string key - the settings/singleton pattern: // one indexed system column instead of a dedicated Props field. var head = await redb.Query() .WhereRedb(o => o.ValueString == "e205:head-of-desk") .FirstOrDefaultAsync(); // 2. Id-set prefilter with Contains - "load these exact objects, filtered further". var byIds = await redb.Query() .WhereRedb(o => seeded.Contains(o.Id)) .ToListAsync(); // 3. The composite shape: a SYSTEM predicate and a Props predicate in one query. // Both are translated to SQL - the numeric key range narrows on _objects, the // department condition narrows on Props values. var itByKey = await redb.Query() .WhereRedb(o => o.Key >= 7000 && o.Key <= 7002) .Where(e => e.Department == "IT") .ToListAsync(); sw.Stop(); // Cleanup: the example leaves no residue behind. await redb.DeleteAsync(seeded); return Ok("E205", "WhereRedb - System Fields and Composition", ExampleTier.Free, sw.ElapsedMilliseconds, byIds.Count + itByKey.Count + (head != null ? 1 : 0), [ $"ValueString lookup: {(head != null ? head.name : "")}", $"Contains(Id) prefilter: {byIds.Count} of {seeded.Count}", $"WhereRedb(Key range).Where(Department==IT): {itByKey.Count}", ]); } } Path: redb/redb.Examples/Examples/E206_WhereRedbNarrowsFirst.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E206_WhereRedbNarrowsFirst.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// WhereRedb narrows first. A condition on the object's own columns (here the parent) is checked /// on _objects before any Props field is read, so the query reads the fields of the few objects /// that pass and nothing else. The same Props filter and page over the whole scheme reads every /// employee. This is the shape of "the points of one route sorted by their number" or "the lines /// of one order": a narrow parent, a Props filter, a page sorted by a Props field. /// [ExampleMeta("E206", "WhereRedb - Narrow by Parent First", "Query", ExampleTier.Free, 1, "WhereRedb", "ParentId", "Performance", "Composite", RelatedApis = ["IRedbQueryable.WhereRedb", "IRedbQueryable.Where", "IRedbQueryable.ToSqlStringAsync"])] public class E206_WhereRedbNarrowsFirst : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // A team lead and twenty employees under it: the parent is a system column (_id_parent), // no Props field is needed to tell the team apart. var lead = new RedbObject { name = "e206-team-lead", Props = new EmployeeProps { FirstName = "E206", LastName = "Lead", Department = "Sales", Salary = 150000m, Age = 45 }, }; var leadId = await redb.SaveAsync(lead); var team = Enumerable.Range(0, 20).Select(i => (IRedbObject)new RedbObject { name = $"e206-member-{i}", parent_id = leadId, Props = new EmployeeProps { FirstName = $"E206-{i}", LastName = "Member", Department = "Sales", Age = 25 + i, Salary = 60000m + i * 2500m, }, }).ToList(); var memberIds = await redb.SaveAsync(team); // The same Props filter and page, once over the whole scheme and once under the parent. var whole = Stopwatch.StartNew(); var anywhere = await redb.Query() .Where(e => e.Salary > 70000m && e.Age >= 30) .OrderByDescending(e => e.Salary) .Take(10) .ToListAsync(); var wholeMs = whole.ElapsedMilliseconds; var underLead = redb.Query() .WhereRedb(o => o.ParentId == leadId) .Where(e => e.Salary > 70000m && e.Age >= 30) .OrderByDescending(e => e.Salary) .Take(10); var narrow = Stopwatch.StartNew(); var teamPage = await underLead.ToListAsync(); var narrowMs = narrow.ElapsedMilliseconds; // The SQL shows where the parent goes: into the scan of _objects that drives the query, // ahead of every Props field. var sql = await underLead.ToSqlStringAsync(); var drivingScan = sql.Split('\n').FirstOrDefault(l => l.Contains("_id_parent"))?.Trim() ?? ""; sw.Stop(); // Cleanup: the example leaves no residue behind. await redb.DeleteAsync(memberIds.Append(leadId).ToList()); return Ok("E206", "WhereRedb - Narrow by Parent First", ExampleTier.Free, sw.ElapsedMilliseconds, teamPage.Count, [ $"Whole scheme, Salary > 70000 and Age >= 30, top 10 by Salary: {wholeMs} ms ({anywhere.Count} rows)", $"Same, WhereRedb(ParentId == lead): {narrowMs} ms ({teamPage.Count} of {team.Count} team members)", $"Driving scan: {drivingScan}", ], sql); } } Path: redb/redb.Examples/Examples/E997_DateTimeJulianVerify.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/E997_DateTimeJulianVerify.cs ---- using System.Diagnostics; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Regression probe for SQLite REAL Julian-day datetime storage. /// Seeds 3 employees with distinct, far-apart HireDates (incl. a fractional time /// of day), then asserts that server-side range filters select EXACTLY the right /// rows and that a saved datetime round-trips. A broken comparison (the old TEXT /// lexical bug) would make ranges always-true/false and fail these assertions. /// [ExampleMeta("E997", "DateTime REAL Julian Verify", "Query", ExampleTier.Free, 1, "Where", "DateTime", "Regression")] public class E997_DateTimeJulianVerify : ExampleBase { private const string Dept = "JULIAN-VERIFY"; public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var lines = new List(); // Idempotent: purge any leftovers from a previous run so the "exactly 1 per range" // asserts hold whether this runs once or as part of the full suite. var stale = await redb.Query().Where(e => e.Department == Dept).Select(e => e.Id).ToListAsync(); if (stale.Count > 0) await redb.DeleteAsync(stale); // Distinct UTC instants, years apart; the 2024 one carries a fractional // time of day to exercise the non-integer part of the Julian day. var dPast = new DateTime(2018, 03, 15, 00, 00, 00, DateTimeKind.Utc); var dMiddle = new DateTime(2024, 06, 15, 13, 45, 30, DateTimeKind.Utc); var dFuture = new DateTime(2030, 09, 20, 00, 00, 00, DateTimeKind.Utc); var seeded = new[] { (dPast, "PAST"), (dMiddle, "MID"), (dFuture, "FUT") } .Select(s => (IRedbObject)new RedbObject { name = $"JulianVerify-{s.Item2}", Props = new EmployeeProps { FirstName = s.Item2, LastName = "Verify", Age = 30, Position = "QA", Department = Dept, Salary = 1m, HireDate = s.Item1, EmployeeCode = $"JV-{s.Item2}" } }) .ToList(); await redb.SaveAsync(seeded); // Range filters — each must return exactly its single seeded match. var midRange = await redb.Query() .Where(e => e.Department == Dept && e.HireDate >= new DateTime(2023, 1, 1) && e.HireDate < new DateTime(2026, 1, 1)) .ToListAsync(); var futureOnly = await redb.Query() .Where(e => e.Department == Dept && e.HireDate >= new DateTime(2029, 1, 1)) .ToListAsync(); var pastOnly = await redb.Query() .Where(e => e.Department == Dept && e.HireDate < new DateTime(2020, 1, 1)) .ToListAsync(); var failures = new List(); void Expect(string label, List> got, string wantCode) { if (got.Count == 1 && got[0].Props.EmployeeCode == $"JV-{wantCode}") lines.Add($"OK {label}: 1 row = {wantCode}"); else failures.Add($"{label}: expected [1×{wantCode}], got [{string.Join(",", got.Select(g => g.Props.EmployeeCode))}]"); } Expect("[2023,2026)", midRange, "MID"); Expect(">=2029", futureOnly, "FUT"); Expect("<2020", pastOnly, "PAST"); // Round-trip: the saved fractional UTC datetime must read back intact. if (midRange.Count == 1) { var rt = midRange[0].Props.HireDate.ToUniversalTime(); var drift = Math.Abs((rt - dMiddle).TotalMilliseconds); if (drift <= 2) lines.Add($"OK round-trip: {rt:yyyy-MM-ddTHH:mm:ss.fff}Z (drift {drift:0.###}ms)"); else failures.Add($"round-trip drift {drift:0.###}ms: got {rt:O}, want {dMiddle:O}"); } sw.Stop(); if (failures.Count > 0) return Fail("E997", "DateTime REAL Julian Verify", ExampleTier.Free, sw.ElapsedMilliseconds, string.Join(" | ", failures)); return Ok("E997", "DateTime REAL Julian Verify", ExampleTier.Free, sw.ElapsedMilliseconds, midRange.Count + futureOnly.Count + pastOnly.Count, lines.ToArray()); } } Path: redb/redb.Examples/Examples/ExampleBase.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Examples/ExampleBase.cs ---- using System.Diagnostics; using redb.Core; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Attribute to mark example classes with metadata. /// Used for parsing examples into ExampleProps for website. /// [AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class ExampleMetaAttribute( string id, string title, string category, ExampleTier tier = ExampleTier.Free, int difficulty = 1, params string[] tags) : Attribute { /// Unique example ID (E001, E010). public string Id { get; } = id; /// Example title for display. public string Title { get; } = title; /// Category for navigation (CRUD, Query, Trees, etc). public string Category { get; } = category; /// License tier (Free, Pro, Enterprise). public ExampleTier Tier { get; } = tier; /// Difficulty level 1-5. public int Difficulty { get; } = difficulty; /// Tags for filtering (SaveAsync, Where, etc). public string[] Tags { get; } = tags; /// Display order on website (set via property). public int Order { get; set; } /// Related API methods for linking to documentation (e.g., "IRedbService.Query", "ITreeQueryable.WhereRoots"). public string[] RelatedApis { get; set; } = []; } /// /// Base class for all examples. /// public abstract class ExampleBase { /// /// The example ids named on the command line, uppercased; null when the whole suite runs. /// Set by Program before any example executes. Lets an example distinguish "I was asked /// for by name" from "the sweep reached me" - E203 seeds only in the former case. /// public static IReadOnlySet? ExplicitlyRequestedIds { get; set; } /// /// Run the example and return result. /// public abstract Task RunAsync(IRedbService redb); /// /// Get metadata from attribute. /// public ExampleMetaAttribute? GetMeta() { return GetType().GetCustomAttributes(typeof(ExampleMetaAttribute), false) .FirstOrDefault() as ExampleMetaAttribute; } /// /// Helper to create success result with count. /// protected static ExampleResult Ok(string id, string title, ExampleTier tier, long elapsedMs, int count, string[] output, string? sql = null) { return new ExampleResult { Id = id, Title = title, Tier = tier, Success = true, ElapsedMs = elapsedMs, Count = count, Output = output, Sql = sql }; } /// /// Helper to create success result without count (for setup/CRUD). /// protected static ExampleResult Ok(string id, string title, ExampleTier tier, long elapsedMs, string[] output, string? sql = null) { return new ExampleResult { Id = id, Title = title, Tier = tier, Success = true, ElapsedMs = elapsedMs, Output = output, Sql = sql }; } /// /// Helper to create failure result. /// protected static ExampleResult Fail(string id, string title, ExampleTier tier, long elapsedMs, string error) { return new ExampleResult { Id = id, Title = title, Tier = tier, Success = false, ElapsedMs = elapsedMs, Output = [], Error = error }; } } Path: redb/redb.Examples/ExamplesEf/E000_BulkInsert_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E000_BulkInsert_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : the same 100 complex employees, mapped to the entity graph by /// hand and written in one SaveChangesAsync with change tracking on. /// [ExampleMeta("E000_ef", "EF: Bulk Insert - Complex Objects", "Setup", ExampleTier.Free, 1, "EF", "BulkInsert")] public class E000_BulkInsert_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); const int count = 100; var headers = E000_BulkInsert.CreateEmployees(count).Select(EmployeeEfMapping.ToEntity).ToList(); db.objects.AddRange(headers); var rows = await db.SaveChangesAsync(); sw.Stop(); return Ok("E000_ef", "EF: Bulk Insert - Complex Objects", ExampleTier.Free, sw.ElapsedMilliseconds, count, [ $"Inserted: {headers.Count} complex objects, {rows} rows", $"Rate: {headers.Count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1)} obj/sec" ]); } } Path: redb/redb.Examples/ExamplesEf/E001_SaveAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E001_SaveAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// EF Core twin of : one new employee, mapped by hand and saved. [ExampleMeta("E001_ef", "EF: SaveAsync - Create Employee", "CRUD", ExampleTier.Free, 1, "EF", "Save")] public class E001_SaveAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var employee = new RedbObject { name = "New Developer", Props = new Biz.EmployeeProps { FirstName = "Alice", LastName = "Johnson", Age = 28, Position = "Developer", Department = "Engineering", Salary = 85000m, HireDate = DateTime.Today, EmployeeCode = "EMP-NEW-001", Skills = ["C#", "React", "SQL"] } }; var header = EmployeeEfMapping.ToEntity(employee); db.objects.Add(header); await db.SaveChangesAsync(); sw.Stop(); return Ok("E001_ef", "EF: SaveAsync - Create Employee", ExampleTier.Free, sw.ElapsedMilliseconds, [$"Created employee ID: {header._id}", $"Name: {employee.Props.FirstName} {employee.Props.LastName}"]); } } Path: redb/redb.Examples/ExamplesEf/E002_LoadAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E002_LoadAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : find any employee, then load it by id, both times as the /// whole business object. /// [ExampleMeta("E002_ef", "EF: Load Employee by ID", "CRUD", ExampleTier.Free, 1, "EF", "Read", "CRUD")] public class E002_LoadAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); // Same first step as E002: one employee, as a whole object. OrderBy is EF's own need: with split // queries and Take, every child query must pick the same rows. var items = await db.EmployeeProps.WithGraph().OrderBy(e => e._id).Take(1).ToListAsync(); var first = items.Select(EmployeeEfGraph.ToBusiness).ToList(); if (first.Count == 0) { sw.Stop(); return Fail("E002_ef", "EF: Load Employee by ID", ExampleTier.Free, sw.ElapsedMilliseconds, "No employees found. Run E203_ef first."); } var id = first[0].Id; var entity = await db.EmployeeProps.WithGraph().FirstOrDefaultAsync(e => e._id == id); var loaded = entity == null ? null : EmployeeEfGraph.ToBusiness(entity); sw.Stop(); return Ok("E002_ef", "EF: Load Employee by ID", ExampleTier.Free, sw.ElapsedMilliseconds, [$"Loaded ID: {loaded?.Id}", $"Employee: {loaded?.Props?.FirstName} {loaded?.Props?.LastName}, {loaded?.Props?.Position}"]); } } Path: redb/redb.Examples/ExamplesEf/E003_UniqueKeys_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E003_UniqueKeys_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a business key that soft delete releases and a typed violation /// naming the key. EF Core has no soft delete and reports a unique violation as a provider exception. /// [ExampleMeta("E003_ef", "EF: Unique Keys - [RedbUnique] and value_unique", "CRUD", ExampleTier.Free, 1, "EF", "Unique")] public class E003_UniqueKeys_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E003_ef", "EF: Unique Keys - [RedbUnique] and value_unique", ExampleTier.Free, "EF Core has no soft delete that releases a unique key and no typed unique violation")); } Path: redb/redb.Examples/ExamplesEf/E004_SubtreeAndElementKeys_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E004_SubtreeAndElementKeys_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : unique keys over the content of a nested class, an /// ordered list and collection elements, plus scheme tags. EF Core has a unique index over columns only. /// [ExampleMeta("E004_ef", "EF: Unique Keys - nested, subtree and element keys, [RedbTags]", "CRUD", ExampleTier.Free, 1, "EF", "Unique")] public class E004_SubtreeAndElementKeys_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E004_ef", "EF: Unique Keys - nested, subtree and element keys, [RedbTags]", ExampleTier.Free, "EF Core has no unique key over the content of a nested class or a list")); } Path: redb/redb.Examples/ExamplesEf/E010_WhereSimple_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E010_WhereSimple_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : up to 100 employees with Salary above 75000, as whole objects. [ExampleMeta("E010_ef", "EF: Where - Filter by Salary", "Query", ExampleTier.Free, 1, "EF", "Where", "Query", "Filter")] public class E010_WhereSimple_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); // OrderBy is EF's own need, redb's query has none: with split queries and Take, every child query // must pick the same 100 employees, or some of them come back without their collections. var entities = await db.EmployeeProps.WithGraph() .Where(e => e.Salary > 75000m) .OrderBy(e => e._id) .Take(100) .ToListAsync(); var result = entities.Select(EmployeeEfGraph.ToBusiness).ToList(); sw.Stop(); return Ok("E010_ef", "EF: Where - Filter by Salary", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Salary > 75000"]); } } Path: redb/redb.Examples/ExamplesEf/E011_WhereAnd_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E011_WhereAnd_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Age >= 30 AND Salary > 70000, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E011_ef", "EF: Where - AND Condition", "Query", ExampleTier.Free, 1, "EF")] public class E011_WhereAnd_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.Age >= 30 && e.Salary > 70000m) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E011_ef", "EF: Where - AND Condition", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Age >= 30 AND Salary > 70000"]); } } Path: redb/redb.Examples/ExamplesEf/E012_WhereOr_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E012_WhereOr_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Age < 30 OR Salary > 90000, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E012_ef", "EF: Where - OR Condition", "Query", ExampleTier.Free, 1, "EF")] public class E012_WhereOr_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.Age < 30 || e.Salary > 90000m) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E012_ef", "EF: Where - OR Condition", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Age < 30 OR Salary > 90000"]); } } Path: redb/redb.Examples/ExamplesEf/E013_WhereNot_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E013_WhereNot_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Position other than Manager, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E013_ef", "EF: Where - NOT Equal", "Query", ExampleTier.Free, 1, "EF")] public class E013_WhereNot_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.Position != "Manager") .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E013_ef", "EF: Where - NOT Equal", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Position != 'Manager'"]); } } Path: redb/redb.Examples/ExamplesEf/E014_WhereRange_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E014_WhereRange_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : 60000 <= Salary < 90000, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E014_ef", "EF: Where - Range Condition", "Query", ExampleTier.Free, 1, "EF")] public class E014_WhereRange_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.Salary >= 60000m && e.Salary < 90000m) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E014_ef", "EF: Where - Range Condition", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: 60k <= Salary < 90k"]); } } Path: redb/redb.Examples/ExamplesEf/E015_WhereTripleAnd_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E015_WhereTripleAnd_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : three conditions, highest salary first, top 100 whole /// employees. Both sides time the same span: the query and the materialization of whole objects. /// [ExampleMeta("E015_ef", "EF: Where - Triple AND", "Query", ExampleTier.Free, 1, "EF")] public class E015_WhereTripleAnd_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.Position != "" && e.Age >= 30 && e.Salary > 70000m) .OrderByDescending(e => e.Salary) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E015_ef", "EF: Where - Triple AND", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Position != '' AND Age >= 30 AND Salary > 70k, ORDER BY Salary DESC, top 100"]); } } Path: redb/redb.Examples/ExamplesEf/E016_WhereChain_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E016_WhereChain_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : three chained Where calls, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E016_ef", "EF: Where - Chained Filters", "Query", ExampleTier.Free, 1, "EF")] public class E016_WhereChain_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.Age >= 30) .Where(e => e.Salary > 60000m) .Where(e => e.Department != "Support") .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E016_ef", "EF: Where - Chained Filters", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: .Where(Age).Where(Salary).Where(Dept)"]); } } Path: redb/redb.Examples/ExamplesEf/E020_DateTimeGreater_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E020_DateTimeGreater_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : hired in the last two years, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// The date is marked UTC: redb stores a DateTime as a UTC clock reading, and Npgsql refuses a local DateTime for a timestamptz column. /// [ExampleMeta("E020_ef", "EF: Where - DateTime Greater", "Query", ExampleTier.Free, 1, "EF")] public class E020_DateTimeGreater_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var cutoffDate = DateTime.SpecifyKind(DateTime.Today.AddYears(-2), DateTimeKind.Utc); var result = await db.EmployeeProps.WithGraph() .Where(e => e.HireDate >= cutoffDate) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E020_ef", "EF: Where - DateTime Greater", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: HireDate >= cutoff"]); } } Path: redb/redb.Examples/ExamplesEf/E021_DateTimeRange_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E021_DateTimeRange_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : hired between three and one year ago, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// The date is marked UTC: redb stores a DateTime as a UTC clock reading, and Npgsql refuses a local DateTime for a timestamptz column. /// [ExampleMeta("E021_ef", "EF: Where - DateTime Range", "Query", ExampleTier.Free, 1, "EF")] public class E021_DateTimeRange_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var startDate = DateTime.SpecifyKind(DateTime.Today.AddYears(-3), DateTimeKind.Utc); var endDate = DateTime.SpecifyKind(DateTime.Today.AddYears(-1), DateTimeKind.Utc); var result = await db.EmployeeProps.WithGraph() .Where(e => e.HireDate >= startDate && e.HireDate < endDate) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E021_ef", "EF: Where - DateTime Range", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: HireDate in [start, end)"]); } } Path: redb/redb.Examples/ExamplesEf/E030_StringContains_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E030_StringContains_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : LastName contains Smith, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E030_ef", "EF: Where - String Contains", "Query", ExampleTier.Free, 1, "EF")] public class E030_StringContains_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.LastName!.Contains("Smith")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E030_ef", "EF: Where - String Contains", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: LastName.Contains('Smith')"]); } } Path: redb/redb.Examples/ExamplesEf/E031_StringStartsWith_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E031_StringStartsWith_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : FirstName starts with John, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E031_ef", "EF: Where - String StartsWith", "Query", ExampleTier.Free, 1, "EF")] public class E031_StringStartsWith_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.FirstName!.StartsWith("John")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E031_ef", "EF: Where - String StartsWith", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: FirstName.StartsWith('John')"]); } } Path: redb/redb.Examples/ExamplesEf/E032_StringContainsIgnoreCase_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E032_StringContainsIgnoreCase_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : LastName contains smith in any case, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// EF Core does not translate Contains with a StringComparison; the PostgreSQL provider's own EF.Functions.ILike is the EF way to say it. /// [ExampleMeta("E032_ef", "EF: Where - Contains IgnoreCase", "Query", ExampleTier.Free, 1, "EF")] public class E032_StringContainsIgnoreCase_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => EF.Functions.ILike(e.LastName!, "%smith%")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E032_ef", "EF: Where - Contains IgnoreCase", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: 'smith' (case-insensitive)"]); } } Path: redb/redb.Examples/ExamplesEf/E040_NestedProperty_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E040_NestedProperty_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : HomeAddress.City is London, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E040_ef", "EF: Where - Nested Property", "Query", ExampleTier.Free, 1, "EF")] public class E040_NestedProperty_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_HomeAddress!.City == "London") .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E040_ef", "EF: Where - Nested Property", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: HomeAddress.City == 'London'"]); } } Path: redb/redb.Examples/ExamplesEf/E041_DeepNested_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E041_DeepNested_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : HomeAddress.Building.Floor above 10, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E041_ef", "EF: Where - Deep Nested Property", "Query", ExampleTier.Free, 1, "EF")] public class E041_DeepNested_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor > 10) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E041_ef", "EF: Where - Deep Nested Property", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: HomeAddress.Building.Floor > 10"]); } } Path: redb/redb.Examples/ExamplesEf/E050_ArrayContains_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E050_ArrayContains_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Skills contains C#, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E050_ef", "EF: Array Contains - Find by Skill", "Query", ExampleTier.Free, 1, "EF")] public class E050_ArrayContains_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_Skills.Any(s => s._value == "C#")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E050_ef", "EF: Array Contains - Find by Skill", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Skills.Contains('C#')"]); } } Path: redb/redb.Examples/ExamplesEf/E051_ArrayMultiple_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E051_ArrayMultiple_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Skills has C# or Python, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E051_ef", "EF: Array Contains - Multiple OR", "Query", ExampleTier.Free, 1, "EF")] public class E051_ArrayMultiple_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_Skills.Any(s => s._value == "C#") || e.EmployeeProps_Skills.Any(s => s._value == "Python")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E051_ef", "EF: Array Contains - Multiple OR", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Skills has 'C#' OR 'Python'"]); } } Path: redb/redb.Examples/ExamplesEf/E052_ArrayNotContains_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E052_ArrayNotContains_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Skills has C# and not intern, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E052_ef", "EF: Array NOT Contains", "Query", ExampleTier.Free, 1, "EF")] public class E052_ArrayNotContains_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_Skills.Any(s => s._value == "C#") && !e.EmployeeProps_Skills.Any(s => s._value == "intern")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E052_ef", "EF: Array NOT Contains", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Skills has 'C#' AND NOT 'intern'"]); } } Path: redb/redb.Examples/ExamplesEf/E053_ArrayWithConditions_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E053_ArrayWithConditions_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Skills has C#, Age >= 30, Salary > 70000, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E053_ef", "EF: Array Contains + Conditions", "Query", ExampleTier.Free, 1, "EF")] public class E053_ArrayWithConditions_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_Skills.Any(s => s._value == "C#") && e.Age >= 30 && e.Salary > 70000m) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E053_ef", "EF: Array Contains + Conditions", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: Skills has 'C#' AND Age >= 30 AND Salary > 70k"]); } } Path: redb/redb.Examples/ExamplesEf/E060_DictContainsKey_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E060_DictContainsKey_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : PhoneDirectory has the key desk, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E060_ef", "EF: Dict ContainsKey - Phone Directory", "Query", ExampleTier.Free, 1, "EF")] public class E060_DictContainsKey_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_PhoneDirectory.Any(d => d._key == "desk")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E060_ef", "EF: Dict ContainsKey - Phone Directory", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: PhoneDirectory.ContainsKey('desk')"]); } } Path: redb/redb.Examples/ExamplesEf/E061_DictIndexer_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E061_DictIndexer_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : BonusByYear[2023] above 6000, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E061_ef", "EF: Dict Indexer - Bonus by Year", "Query", ExampleTier.Free, 1, "EF")] public class E061_DictIndexer_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_BonusByYear.Any(d => d._key == 2023 && d._value > 6000m)) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E061_ef", "EF: Dict Indexer - Bonus by Year", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: BonusByYear[2023] > 6000"]); } } Path: redb/redb.Examples/ExamplesEf/E062_DictNestedClass_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E062_DictNestedClass_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : OfficeLocations[HQ].City is New York, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E062_ef", "EF: Dict - Nested Class Property", "Query", ExampleTier.Free, 1, "EF")] public class E062_DictNestedClass_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_OfficeLocations.Any(o => o._key == "HQ" && o.City == "New York")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E062_ef", "EF: Dict - Nested Class Property", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: OfficeLocations['HQ'].City == 'New York'"]); } } Path: redb/redb.Examples/ExamplesEf/E063_DictTupleKey_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E063_DictTupleKey_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : PerformanceReviews[(2024, Q1)] is Excellent, up to 100 whole employees. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E063_ef", "EF: Dict - Tuple Key", "Query", ExampleTier.Free, 1, "EF")] public class E063_DictTupleKey_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .Where(e => e.EmployeeProps_PerformanceReviews.Any(r => r._key_Item1 == 2024 && r._key_Item2 == "Q1" && r._value == "Excellent")) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E063_ef", "EF: Dict - Tuple Key", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Filter: PerformanceReviews[(2024, 'Q1')] == 'Excellent'"]); } } Path: redb/redb.Examples/ExamplesEf/E070_CountAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E070_CountAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : total and filtered count. [ExampleMeta("E070_ef", "EF: CountAsync - Total and Filtered", "Query", ExampleTier.Free, 1, "EF", "Count")] public class E070_CountAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var totalCount = await db.EmployeeProps.CountAsync(); var managersCount = await db.EmployeeProps.Where(e => e.Position == "Manager").CountAsync(); var highFloorCount = await db.EmployeeProps .Where(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor > 20) .CountAsync(); sw.Stop(); return Ok("E070_ef", "EF: CountAsync - Total and Filtered", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Total: {totalCount}, Managers: {managersCount}, Home floor above 20: {highFloorCount}"]); } } Path: redb/redb.Examples/ExamplesEf/E071_AnyAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E071_AnyAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : does any employee exist. [ExampleMeta("E071_ef", "EF: AnyAsync - Check Existence", "Query", ExampleTier.Free, 1, "EF")] public class E071_AnyAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var anyExist = await db.EmployeeProps.AnyAsync(); var anyOnTopFloor = await db.EmployeeProps .Where(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor == 30) .AnyAsync(); sw.Stop(); return Ok("E071_ef", "EF: AnyAsync - Check Existence", ExampleTier.Free, sw.ElapsedMilliseconds, anyExist ? 1 : 0, [$"Any employees exist: {anyExist}", $"Any living on floor 30: {anyOnTopFloor}"]); } } Path: redb/redb.Examples/ExamplesEf/E072_AnyWithPredicate_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E072_AnyWithPredicate_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : is there anyone with Salary above 100000. [ExampleMeta("E072_ef", "EF: AnyAsync - With Predicate", "Query", ExampleTier.Free, 1, "EF")] public class E072_AnyWithPredicate_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var anyHighEarners = await db.EmployeeProps.AnyAsync(e => e.Salary > 100_000m); var anyBerlinHighFloor = await db.EmployeeProps.AnyAsync(e => e.EmployeeProps_HomeAddress!.City == "Berlin" && e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor > 25); sw.Stop(); return Ok("E072_ef", "EF: AnyAsync - With Predicate", ExampleTier.Free, sw.ElapsedMilliseconds, anyHighEarners ? 1 : 0, [$"Any with Salary > 100k: {anyHighEarners}", $"Any in Berlin above floor 25: {anyBerlinHighFloor}"]); } } Path: redb/redb.Examples/ExamplesEf/E073_AllAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E073_AllAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : three AllAsync checks. [ExampleMeta("E073_ef", "EF: AllAsync - Check All Match", "Query", ExampleTier.Free, 1, "EF")] public class E073_AllAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var allNonNegativeSalary = await db.EmployeeProps.AllAsync(e => e.Salary >= 0); var allHighEarnersOver25 = await db.EmployeeProps.Where(e => e.Salary > 100000m).AllAsync(e => e.Age > 25); var allMillionaires = await db.EmployeeProps.AllAsync(e => e.Salary > 1_000_000m); var allBerlinFloorsValid = await db.EmployeeProps .Where(e => e.EmployeeProps_HomeAddress!.City == "Berlin") .AllAsync(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor >= 1); sw.Stop(); var passedCount = new[] { allNonNegativeSalary, allHighEarnersOver25, allBerlinFloorsValid }.Count(c => c); return Ok("E073_ef", "EF: AllAsync - Check All Match", ExampleTier.Free, sw.ElapsedMilliseconds, passedCount, [$"All Salary >= 0: {allNonNegativeSalary}", $"All high earners (>100k) over 25: {allHighEarnersOver25}", $"All millionaires (>1M): {allMillionaires} (expected false)", $"All in Berlin on floor 1 or higher: {allBerlinFloorsValid}"]); } } Path: redb/redb.Examples/ExamplesEf/E074_WhereIn_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E074_WhereIn_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : employees of three departments, up to 100 whole objects, /// and their total count. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E074_ef", "EF: WhereIn - Filter by List", "Query", ExampleTier.Free, 1, "EF")] public class E074_WhereIn_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var targetDepartments = new[] { "Engineering", "Sales", "Marketing" }; var results = await db.EmployeeProps.WithGraph() .Where(e => targetDepartments.Contains(e.Department)) .OrderBy(e => e._id) .Take(100) .ToBusinessListAsync(); var totalCount = await db.EmployeeProps.Where(e => targetDepartments.Contains(e.Department)).CountAsync(); sw.Stop(); return Ok("E074_ef", "EF: WhereIn - Filter by List", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, [$"Loaded: {results.Count}, Total: {totalCount}", $"Depts: {string.Join(", ", targetDepartments)}"]); } } Path: redb/redb.Examples/ExamplesEf/E075_Select_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E075_Select_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : ten fields of 100 employees from every depth, a projection, no /// whole object. Nested classes cost EF a join per level, dictionary entries a subquery by key. Without /// tracking by nature: there is no entity to track. /// [ExampleMeta("E075_ef", "EF: Select - Projection", "Query", ExampleTier.Free, 1, "EF")] public class E075_Select_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var results = await db.EmployeeProps .Where(x => x.Salary > 60000m && x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor > 10) .OrderByDescending(x => x.Salary) .ThenBy(x => x.LastName) .Take(100) .Select(x => new { // Level 0: columns of the employee table x.FirstName, x.LastName, x.Salary, // Level 1: one join each HomeCity = x.EmployeeProps_HomeAddress!.City, WorkCity = x.EmployeeProps_WorkAddress!.City, // Level 2: two joins each HomeFloor = x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor, WorkBuilding = x.EmployeeProps_WorkAddress!.EmployeeProps_WorkAddress_Building!.Name, // Dictionary entries: a subquery by key each DeskPhone = x.EmployeeProps_PhoneDirectory.Where(p => p._key == "desk").Select(p => p._value).FirstOrDefault(), HqCity = x.EmployeeProps_OfficeLocations.Where(o => o._key == "HQ").Select(o => o.City).FirstOrDefault(), HqFloor = x.EmployeeProps_OfficeLocations.Where(o => o._key == "HQ") .Select(o => o.EmployeeProps_OfficeLocations_Building!.Floor).FirstOrDefault() }) .ToListAsync(); sw.Stop(); var first = results.FirstOrDefault(); var fullName = first != null ? $"{first.FirstName} {first.LastName}" : "N/A"; return Ok("E075_ef", "EF: Select - Projection", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Salary > 60000 AND HomeAddress.Building.Floor > 10, ORDER BY Salary DESC, LastName", $"Projected: {results.Count}", $"First: {fullName}, Salary: {first?.Salary:N0}", $"Home: {first?.HomeCity}, floor {first?.HomeFloor}; Work: {first?.WorkCity}, {first?.WorkBuilding}", $"Desk phone: {first?.DeskPhone}; HQ: {first?.HqCity}, floor {first?.HqFloor}"]); } } Path: redb/redb.Examples/ExamplesEf/E076_Distinct_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E076_Distinct_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . redb removes objects whose whole content is the same. In EF the content of an employee is spread over some forty tables; Distinct on an entity query compares the rows of the root table, key included, so it never removes anything. Comparing whole graphs would mean grouping by every column of every table, which no EF query expresses. /// [ExampleMeta("E076_ef", "EF: Distinct - Unique by Props", "Query", ExampleTier.Free, 1, "EF")] public class E076_Distinct_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E076_ef", "EF: Distinct - Unique by Props", ExampleTier.Free, "EF Core has no distinct by the content of a whole object graph")); } Path: redb/redb.Examples/ExamplesEf/E080_OrderBy_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E080_OrderBy_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : five lowest and five highest salaries, whole employees. [ExampleMeta("E080_ef", "EF: OrderBy - Sort by Salary", "Query", ExampleTier.Free, 1, "EF")] public class E080_OrderBy_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var lowest = await db.EmployeeProps.WithGraph().OrderBy(e => e.Salary).Take(5).ToBusinessListAsync(); var highest = await db.EmployeeProps.WithGraph().OrderByDescending(e => e.Salary).Take(5).ToBusinessListAsync(); sw.Stop(); var lowestSalary = lowest.FirstOrDefault()?.Props?.Salary ?? 0; var highestSalary = highest.FirstOrDefault()?.Props?.Salary ?? 0; return Ok("E080_ef", "EF: OrderBy - Sort by Salary", ExampleTier.Free, sw.ElapsedMilliseconds, lowest.Count + highest.Count, [$"Lowest: ${lowestSalary:N0}, Highest: ${highestSalary:N0}"]); } } Path: redb/redb.Examples/ExamplesEf/E081_OrderByThenBy_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E081_OrderByThenBy_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : Department ascending, Salary descending, first 100 whole employees. /// [ExampleMeta("E081_ef", "EF: OrderBy + ThenBy", "Query", ExampleTier.Free, 1, "EF")] public class E081_OrderByThenBy_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .OrderBy(e => e.Department) .ThenByDescending(e => e.Salary) .Take(100) .ToBusinessListAsync(); sw.Stop(); return Ok("E081_ef", "EF: OrderBy + ThenBy", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Sort: Department ASC, Salary DESC"]); } } Path: redb/redb.Examples/ExamplesEf/E082_SkipTake_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E082_SkipTake_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : page 2 of 10 by LastName, whole employees. /// [ExampleMeta("E082_ef", "EF: Skip/Take - Pagination", "Query", ExampleTier.Free, 1, "EF")] public class E082_SkipTake_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var result = await db.EmployeeProps.WithGraph() .OrderBy(e => e.LastName) .Skip(10) .Take(10) .ToBusinessListAsync(); sw.Stop(); return Ok("E082_ef", "EF: Skip/Take - Pagination", ExampleTier.Free, sw.ElapsedMilliseconds, result.Count, ["Page 2, size 10"]); } } Path: redb/redb.Examples/ExamplesEf/E083_OrderByDescending_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E083_OrderByDescending_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : five top earners and five oldest, whole employees. [ExampleMeta("E083_ef", "EF: OrderByDescending - Reverse Sort", "Query", ExampleTier.Free, 1, "EF")] public class E083_OrderByDescending_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var topEarners = await db.EmployeeProps.WithGraph().OrderByDescending(e => e.Salary).Take(5).ToBusinessListAsync(); var oldest = await db.EmployeeProps.WithGraph().OrderByDescending(e => e.Age).Take(5).ToBusinessListAsync(); sw.Stop(); var topSalary = topEarners.FirstOrDefault()?.Props?.Salary ?? 0; var oldestAge = oldest.FirstOrDefault()?.Props?.Age ?? 0; return Ok("E083_ef", "EF: OrderByDescending - Reverse Sort", ExampleTier.Free, sw.ElapsedMilliseconds, topEarners.Count + oldest.Count, [$"Top salary: ${topSalary:N0}", $"Oldest age: {oldestAge}"]); } } Path: redb/redb.Examples/ExamplesEf/E087_TreeCleanup_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E087_TreeCleanup_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : every department node loaded, then removed. EF has no trash, /// so the nodes are deleted for good (the cascade on _id_parent and on the Props rows does the rest). /// [ExampleMeta("E087_ef", "EF: Tree Cleanup - Remove All", "Trees", ExampleTier.Free, 1, "EF", "Tree", "Delete")] public class E087_TreeCleanup_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var existing = (await db.Nodes().ToListAsync()).Select(DepartmentEfMapping.ToBusiness).ToList(); var count = existing.Count; if (count > 0) await db.objects.Where(o => o._id_scheme == EfSchemeIds.Department).ExecuteDeleteAsync(); sw.Stop(); return Ok("E087_ef", "EF: Tree Cleanup - Remove All", ExampleTier.Free, sw.ElapsedMilliseconds, count, [count > 0 ? $"Deleted: {count} tree nodes" : "No tree data to delete"]); } } Path: redb/redb.Examples/ExamplesEf/E088_TreeCreateBulk_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E088_TreeCreateBulk_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; using Tree = redb.Examples.Examples.E088_TreeCreateBulk; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : the same four-level department tree, built as one entity /// graph (children point at their parent entity) and written by one SaveChangesAsync. /// [ExampleMeta("E088_ef", "EF: Tree Create BULK - Fast", "Trees", ExampleTier.Free, 1, "EF", "Tree", "BulkInsert")] public class E088_TreeCreateBulk_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var nodes = new List(); var root = DepartmentEfMapping.ToEntity("TechCorp", "CORP", "Headquarters", 50_000_000m, null); nodes.Add(root); var offices = new objects[Tree.OfficeCount]; for (int i = 0; i < Tree.OfficeCount; i++) { var city = Tree.Cities[i % Tree.Cities.Length]; offices[i] = DepartmentEfMapping.ToEntity($"{city} Office", $"OFF-{i + 1:D2}", $"Regional office {city}", 5_000_000m - i * 200_000m, root); nodes.Add(offices[i]); } var depts = new List(); for (int o = 0; o < Tree.OfficeCount; o++) { for (int d = 0; d < Tree.DeptPerOffice; d++) { var deptName = Tree.Departments[d % Tree.Departments.Length]; var dept = DepartmentEfMapping.ToEntity($"{deptName} {o + 1}-{d + 1}", $"DEPT-{o + 1:D2}-{d + 1:D2}", deptName, 1_000_000m - d * 100_000m, offices[o]); depts.Add(dept); nodes.Add(dept); } } for (int d = 0; d < Tree.TeamsForFirstDepts && d < depts.Count; d++) { for (int t = 0; t < Tree.TeamsPerDept; t++) { var teamName = Tree.Teams[t % Tree.Teams.Length]; nodes.Add(DepartmentEfMapping.ToEntity($"{teamName} Team {d + 1}-{t + 1}", $"TEAM-{d + 1:D2}-{t + 1:D2}", teamName, 300_000m - t * 50_000m, depts[d])); } } db.objects.AddRange(nodes); await db.SaveChangesAsync(); sw.Stop(); var rate = nodes.Count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1); return Ok("E088_ef", "EF: Tree Create BULK - Fast", ExampleTier.Free, sw.ElapsedMilliseconds, nodes.Count, [$"Bulk created: {nodes.Count} tree nodes in 4 levels", $"Rate: {rate} nodes/sec"]); } } Path: redb/redb.Examples/ExamplesEf/E089_TreeCreate_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E089_TreeCreate_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; using Tree = redb.Examples.Examples.E088_TreeCreateBulk; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : the same tree saved node by node, one SaveChangesAsync /// per node, the antipattern on purpose as in redb. /// [ExampleMeta("E089_ef", "EF: Tree Create Sequential - ANTIPATTERN (slow by design)", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E089_TreeCreate_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var count = 0; async Task Save(objects node) { db.objects.Add(node); await db.SaveChangesAsync(); count++; return node; } var root = await Save(DepartmentEfMapping.ToEntity("TechCorp", "CORP", "Headquarters", 50_000_000m, null)); var offices = new objects[Tree.OfficeCount]; for (int i = 0; i < Tree.OfficeCount; i++) { var city = Tree.Cities[i % Tree.Cities.Length]; offices[i] = await Save(DepartmentEfMapping.ToEntity($"{city} Office", $"OFF-{i + 1:D2}", $"Regional office {city}", 5_000_000m - i * 200_000m, root)); } var depts = new List(); for (int o = 0; o < Tree.OfficeCount; o++) { for (int d = 0; d < Tree.DeptPerOffice; d++) { var deptName = Tree.Departments[d % Tree.Departments.Length]; depts.Add(await Save(DepartmentEfMapping.ToEntity($"{deptName} {o + 1}-{d + 1}", $"DEPT-{o + 1:D2}-{d + 1:D2}", deptName, 1_000_000m - d * 100_000m, offices[o]))); } } for (int d = 0; d < Tree.TeamsForFirstDepts && d < depts.Count; d++) { for (int t = 0; t < Tree.TeamsPerDept; t++) { var teamName = Tree.Teams[t % Tree.Teams.Length]; await Save(DepartmentEfMapping.ToEntity($"{teamName} Team {d + 1}-{t + 1}", $"TEAM-{d + 1:D2}-{t + 1:D2}", teamName, 300_000m - t * 50_000m, depts[d])); } } sw.Stop(); var rate = count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1); return Ok("E089_ef", "EF: Tree Create Sequential - ANTIPATTERN (slow by design)", ExampleTier.Free, sw.ElapsedMilliseconds, count, [ "ANTIPATTERN: one SaveChanges round-trip per node, slow on purpose.", $"Sequential created: {count} tree nodes in 4 levels", $"Rate: {rate} nodes/sec - compare with E088_ef (one SaveChanges)" ]); } } Path: redb/redb.Examples/ExamplesEf/E090_TreeLoad_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E090_TreeLoad_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a subtree loaded to a given depth. [ExampleMeta("E090_ef", "EF: Tree Load - Full Hierarchy", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E090_TreeLoad_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E090_ef", "EF: Tree Load - Full Hierarchy", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E091_TreeCount_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E091_TreeCount_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the count of department nodes. [ExampleMeta("E091_ef", "EF: Tree Count - CountAsync", "Trees", ExampleTier.Free, 1, "EF", "Tree", "Count")] public class E091_TreeCount_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var count = await db.DepartmentProps.CountAsync(); sw.Stop(); if (count == 0) return Fail("E091_ef", "EF: Tree Count - CountAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No tree. Run E088_ef first."); return Ok("E091_ef", "EF: Tree Count - CountAsync", ExampleTier.Free, sw.ElapsedMilliseconds, count, ["DepartmentProps.CountAsync()", $"Total: {count} nodes"]); } } Path: redb/redb.Examples/ExamplesEf/E092_TreeChildren_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E092_TreeChildren_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the CORP root and its direct children (_id_parent equal to the root). [ExampleMeta("E092_ef", "EF: Tree Children - Direct", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E092_TreeChildren_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var rootEntity = await db.Nodes().Where(d => d.Code == "CORP").OrderBy(d => d._id).FirstOrDefaultAsync(); if (rootEntity == null) return Ok("E092_ef", "EF: Tree Children - Direct", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No tree found. Run E088_ef first."]); var root = DepartmentEfMapping.ToBusiness(rootEntity); var childList = (await db.Nodes().Where(d => d.objects._id_parent == root.id).ToListAsync()) .Select(DepartmentEfMapping.ToBusiness).ToList(); sw.Stop(); var names = childList.Select(c => c.name).ToArray(); return Ok("E092_ef", "EF: Tree Children - Direct", ExampleTier.Free, sw.ElapsedMilliseconds, childList.Count, [ $"Parent: {root.name} ({root.Props.Code})", $"Children: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/ExamplesEf/E093_TreePath_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E093_TreePath_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the path from a node up to the root. [ExampleMeta("E093_ef", "EF: Tree Path - Breadcrumbs", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E093_TreePath_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E093_ef", "EF: Tree Path - Breadcrumbs", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E094_TreeDescendants_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E094_TreeDescendants_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . All descendants of a node, at any depth, need a /// recursive query (WITH RECURSIVE); EF Core has no LINQ translation for it. The alternatives are raw SQL /// or loading level by level with a round trip per level, neither of which answers in one query as redb does. /// [ExampleMeta("E094_ef", "EF: Tree Descendants - All", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E094_TreeDescendants_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E094_ef", "EF: Tree Descendants - All", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for descendants at any depth")); } Path: redb/redb.Examples/ExamplesEf/E095_TreeMove_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E095_TreeMove_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a department moved under OFF-02 and back under OFF-01 by changing /// its _id_parent, saved each time. Its subtree follows, since the children point at it. /// [ExampleMeta("E095_ef", "EF: Tree Move - Relocate Node", "Trees", ExampleTier.Free, 1, "EF", "Tree", "Update")] public class E095_TreeMove_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var dept = await db.Nodes().Where(d => d.Code!.StartsWith("DEPT-01-")).OrderBy(d => d._id).FirstOrDefaultAsync(); if (dept == null) return Ok("E095_ef", "EF: Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No tree found. Run E088_ef first."]); var targetOffice = await db.Nodes().Where(d => d.Code == "OFF-02").OrderBy(d => d._id).FirstOrDefaultAsync(); if (targetOffice == null) return Ok("E095_ef", "EF: Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["Target office not found."]); var originalParentId = dept.objects._id_parent; dept.objects._id_parent = targetOffice._id; dept.objects._date_modify = DateTime.UtcNow; await db.SaveChangesAsync(); if (originalParentId.HasValue) { var origOffice = await db.Nodes().Where(d => d.Code == "OFF-01").OrderBy(d => d._id).FirstOrDefaultAsync(); if (origOffice != null) { dept.objects._id_parent = origOffice._id; dept.objects._date_modify = DateTime.UtcNow; await db.SaveChangesAsync(); } } sw.Stop(); return Ok("E095_ef", "EF: Tree Move - Relocate Node", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [ $"Moved: {dept.objects._name} to {targetOffice.objects._name}", "Moved back to original office", "Subtree preserved during move" ]); } } Path: redb/redb.Examples/ExamplesEf/E096_TreeQuery_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E096_TreeQuery_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : department nodes whose name contains "IT", ordered by name. [ExampleMeta("E096_ef", "EF: Tree Query - LINQ on Trees", "Trees", ExampleTier.Free, 1, "EF", "Tree", "Where")] public class E096_TreeQuery_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var itDepts = (await db.Nodes().Where(d => d.Name!.Contains("IT")).OrderBy(d => d.Name).ToListAsync()) .Select(DepartmentEfMapping.ToBusiness).ToList(); sw.Stop(); var names = itDepts.Select(d => $"{d.Props.Name} ({d.Props.Code})").ToArray(); return Ok("E096_ef", "EF: Tree Query - LINQ on Trees", ExampleTier.Free, sw.ElapsedMilliseconds, itDepts.Count, [ "Filter: Name.Contains('IT')", $"Found: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/ExamplesEf/E097_TreeQueryRoots_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E097_TreeQueryRoots_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : department nodes without a parent. [ExampleMeta("E097_ef", "EF: Tree Query - Roots Only", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E097_TreeQueryRoots_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var roots = (await db.Nodes().Where(d => d.objects._id_parent == null).ToListAsync()) .Select(DepartmentEfMapping.ToBusiness).ToList(); sw.Stop(); var names = roots.Select(r => $"{r.Props.Name} ({r.Props.Code})").ToArray(); return Ok("E097_ef", "EF: Tree Query - Roots Only", ExampleTier.Free, sw.ElapsedMilliseconds, roots.Count, [ "Filter: _id_parent IS NULL", $"Found: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/ExamplesEf/E098_TreeQueryLeaves_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E098_TreeQueryLeaves_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : department nodes that have no children. [ExampleMeta("E098_ef", "EF: Tree Query - Leaves Only", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E098_TreeQueryLeaves_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var leaves = (await db.Nodes().Where(d => !d.objects.Inverse_id_parentNavigation.Any()).ToListAsync()) .Select(DepartmentEfMapping.ToBusiness).ToList(); sw.Stop(); var names = leaves.Select(l => $"{l.Props.Name} ({l.Props.Code})").ToArray(); return Ok("E098_ef", "EF: Tree Query - Leaves Only", ExampleTier.Free, sw.ElapsedMilliseconds, leaves.Count, [ "Filter: no children (NOT EXISTS child)", $"Found: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/ExamplesEf/E099_TreeQueryLevel_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E099_TreeQueryLevel_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the nodes at a given level below a root. [ExampleMeta("E099_ef", "EF: Tree Query - By Level", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E099_TreeQueryLevel_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E099_ef", "EF: Tree Query - By Level", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E100_TreeTraversalDFS_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E100_TreeTraversalDFS_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : depth-first walk over a tree loaded to a given depth. [ExampleMeta("E100_ef", "EF: Tree Traversal - DFS", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E100_TreeTraversalDFS_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E100_ef", "EF: Tree Traversal - DFS", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E101_TreeTraversalBFS_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E101_TreeTraversalBFS_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : breadth-first walk over a tree loaded to a given depth. [ExampleMeta("E101_ef", "EF: Tree Traversal - BFS", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E101_TreeTraversalBFS_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E101_ef", "EF: Tree Traversal - BFS", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E102_TreeIsDescendant_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E102_TreeIsDescendant_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : whether a node lies anywhere below another. [ExampleMeta("E102_ef", "EF: Tree - IsDescendantOf", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E102_TreeIsDescendant_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E102_ef", "EF: Tree - IsDescendantOf", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E103_TreeIsAncestor_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E103_TreeIsAncestor_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : whether a node lies anywhere above another. [ExampleMeta("E103_ef", "EF: Tree - IsAncestorOf", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E103_TreeIsAncestor_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E103_ef", "EF: Tree - IsAncestorOf", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E104_TreeGetLevel_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E104_TreeGetLevel_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the depth of a node from its root. [ExampleMeta("E104_ef", "EF: Tree - GetLevel", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E104_TreeGetLevel_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E104_ef", "EF: Tree - GetLevel", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E105_TreeQueryWithRoot_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E105_TreeQueryWithRoot_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a subtree query limited to a given depth. [ExampleMeta("E105_ef", "EF: Tree Query - Scoped to Root", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E105_TreeQueryWithRoot_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E105_ef", "EF: Tree Query - Scoped to Root", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E106_TreeQueryChildrenOf_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E106_TreeQueryChildrenOf_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the direct children of the CORP root. The root lookup is outside the measurement. [ExampleMeta("E106_ef", "EF: Tree Query - WhereChildrenOf", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E106_TreeQueryChildrenOf_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { await using var db = await contexts.CreateDbContextAsync(); var rootId = await db.Nodes().Where(d => d.Code == "CORP").OrderBy(d => d._id).Select(d => (long?)d._id).FirstOrDefaultAsync(); if (rootId == null) return Fail("E106_ef", "EF: Tree Query - WhereChildrenOf", ExampleTier.Free, 0, "No tree. Run E088_ef first."); var sw = Stopwatch.StartNew(); var children = (await db.Nodes().Where(d => d.objects._id_parent == rootId).ToListAsync()) .Select(DepartmentEfMapping.ToBusiness).ToList(); sw.Stop(); var names = children.Take(5).Select(c => c.Props.Code).ToArray(); return Ok("E106_ef", "EF: Tree Query - WhereChildrenOf", ExampleTier.Free, sw.ElapsedMilliseconds, children.Count, [ $"Direct children of CORP: {children.Count}", $"Codes: {string.Join(", ", names)}" ]); } } Path: redb/redb.Examples/ExamplesEf/E107_TreeQueryMultiRoot_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E107_TreeQueryMultiRoot_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : subtrees of several roots limited to a given depth. [ExampleMeta("E107_ef", "EF: Tree Query - Multiple Roots", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E107_TreeQueryMultiRoot_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E107_ef", "EF: Tree Query - Multiple Roots", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E108_TreeToTreeList_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E108_TreeToTreeList_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : found nodes with their parent chain up to the root. [ExampleMeta("E108_ef", "EF: Tree Query - ToTreeListAsync", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E108_TreeToTreeList_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E108_ef", "EF: Tree Query - ToTreeListAsync", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E109_TreeToRootList_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E109_TreeToRootList_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : whole trees assembled from their roots. [ExampleMeta("E109_ef", "EF: Tree Query - ToRootListAsync", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E109_TreeToRootList_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E109_ef", "EF: Tree Query - ToRootListAsync", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E110_TreeWhereHasAncestor_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E110_TreeWhereHasAncestor_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : nodes filtered by a condition on any ancestor. [ExampleMeta("E110_ef", "EF: Tree Query - WhereHasAncestor", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E110_TreeWhereHasAncestor_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E110_ef", "EF: Tree Query - WhereHasAncestor", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E111_TreeWhereHasDescendant_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E111_TreeWhereHasDescendant_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : nodes filtered by a condition on any descendant. [ExampleMeta("E111_ef", "EF: Tree Query - WhereHasDescendant", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E111_TreeWhereHasDescendant_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E111_ef", "EF: Tree Query - WhereHasDescendant", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E112_TreeStats_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E112_TreeStats_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : statistics of a tree loaded to a given depth. [ExampleMeta("E112_ef", "EF: Tree - GetStats", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E112_TreeStats_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E112_ef", "EF: Tree - GetStats", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E113_TreeToFlatList_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E113_TreeToFlatList_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a filtered subtree limited to a given depth, as a flat list. [ExampleMeta("E113_ef", "EF: Tree Query - ToFlatListAsync", "Trees", ExampleTier.Free, 1, "EF", "Tree")] public class E113_TreeToFlatList_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E113_ef", "EF: Tree Query - ToFlatListAsync", ExampleTier.Free, "EF Core has no tree query with a depth parameter: every depth needs its own hand-written chain of navigations")); } Path: redb/redb.Examples/ExamplesEf/E114_ListCreate_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E114_ListCreate_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : the list "ExampleStatuses" created anew. An earlier one is /// removed first, with the person fields that point at its items, as redb removes those values. /// [ExampleMeta("E114_ef", "EF: List - Create", "List", ExampleTier.Free, 1, "EF", "List")] public class E114_ListCreate_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var existing = await db.lists.FirstOrDefaultAsync(l => l._name == "ExampleStatuses"); if (existing != null) { var itemIds = await db.list_items.Where(i => i._id_list == existing._id).Select(i => i._id).ToListAsync(); if (itemIds.Count > 0) { await db.PersonProps.Where(p => p.Status != null && itemIds.Contains(p.Status.Value)) .ExecuteUpdateAsync(s => s.SetProperty(p => p.Status, (long?)null)); await db.PersonProps_Roles.Where(r => r._value != null && itemIds.Contains(r._value.Value)) .ExecuteDeleteAsync(); } // The items go with the list through the cascade on _id_list. await db.lists.Where(l => l._id == existing._id).ExecuteDeleteAsync(); } var savedList = new lists { _name = "ExampleStatuses", _alias = "Example Statuses" }; db.lists.Add(savedList); await db.SaveChangesAsync(); sw.Stop(); return Ok("E114_ef", "EF: List - Create", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"List ID: {savedList._id}", $"Name: {savedList._name}", $"Alias: {savedList._alias ?? "N/A"}"]); } } Path: redb/redb.Examples/ExamplesEf/E115_ListAddItems_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E115_ListAddItems_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : four items with aliases added to "ExampleStatuses" in one save. [ExampleMeta("E115_ef", "EF: List - Add Items", "List", ExampleTier.Free, 1, "EF", "List")] public class E115_ListAddItems_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var list = await db.lists.FirstOrDefaultAsync(l => l._name == "ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E115_ef", "EF: List - Add Items", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114_ef first."); } var values = new List { "Active", "Inactive", "Pending", "Blocked" }; var aliases = new List { "Active status", "Inactive status", "Pending review", "Blocked access" }; var addedItems = values.Select((v, i) => new list_items { _id_list = list._id, _value = v, _alias = aliases[i] }).ToList(); db.list_items.AddRange(addedItems); await db.SaveChangesAsync(); sw.Stop(); var itemsList = string.Join(", ", addedItems.Select(i => i._value)); return Ok("E115_ef", "EF: List - Add Items", ExampleTier.Free, sw.ElapsedMilliseconds, addedItems.Count, [$"Added: {addedItems.Count} items", $"Values: {itemsList}"]); } } Path: redb/redb.Examples/ExamplesEf/E116_ListGetByName_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E116_ListGetByName_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the list found by name, then its items, two queries as in redb. [ExampleMeta("E116_ef", "EF: List - Get Items", "List", ExampleTier.Free, 1, "EF", "List")] public class E116_ListGetByName_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var list = await db.lists.FirstOrDefaultAsync(l => l._name == "ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E116_ef", "EF: List - Get Items", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114_ef first."); } var items = (await db.list_items.Where(i => i._id_list == list._id).OrderBy(i => i._id).ToListAsync()) .Select(PersonEfMapping.ToItem).ToList(); sw.Stop(); var itemsPreview = string.Join(", ", items.Take(3).Select(i => i.Value)); if (items.Count > 3) itemsPreview += "..."; return Ok("E116_ef", "EF: List - Get Items", ExampleTier.Free, sw.ElapsedMilliseconds, items.Count, [$"List: {list._name} (ID: {list._id})", $"Items: {itemsPreview}"]); } } Path: redb/redb.Examples/ExamplesEf/E117_ListItemWithObject_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E117_ListItemWithObject_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a city saved with its coordinates, then a list item /// "Capital" that points at it, saved together. /// [ExampleMeta("E117_ef", "EF: ListItem - With Object", "List", ExampleTier.Free, 1, "EF", "List")] public class E117_ListItemWithObject_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var list = await db.lists.FirstOrDefaultAsync(l => l._name == "ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E117_ef", "EF: ListItem - With Object", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114_ef first."); } var now = DateTime.UtcNow; var city = new objects { _id_scheme = EfSchemeIds.City, _date_create = now, _date_modify = now, _name = "Moscow", CityProps = new CityProps { Name = "Moscow", Population = 12_655_000, Region = "Central Federal District", IsCapital = true, CityProps_Coordinates = [ new CityProps_Coordinates { _idx = 0, _value = 55.7558 }, new CityProps_Coordinates { _idx = 1, _value = 37.6173 } ] } }; var item = new list_items { _id_list = list._id, _value = "Capital", _alias = "Capital city status", _id_objectNavigation = city }; db.list_items.Add(item); await db.SaveChangesAsync(); sw.Stop(); return Ok("E117_ef", "EF: ListItem - With Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Item: {item._value} (ID: {item._id})", $"Linked object ID: {item._id_object}"]); } } Path: redb/redb.Examples/ExamplesEf/E118_PropsListItemField_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E118_PropsListItemField_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a person whose Status points at the item "Active", /// saved and loaded back whole with the item included. /// [ExampleMeta("E118_ef", "EF: Props - ListItem Field", "List", ExampleTier.Free, 1, "EF", "List")] public class E118_PropsListItemField_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); long personId; await using (var db = await contexts.CreateDbContextAsync()) { var list = await db.lists.FirstOrDefaultAsync(l => l._name == "ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E118_ef", "EF: Props - ListItem Field", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114_ef first."); } var items = await db.list_items.Where(i => i._id_list == list._id).ToListAsync(); var activeStatus = items.FirstOrDefault(i => i._value == "Active"); if (activeStatus == null) { sw.Stop(); return Fail("E118_ef", "EF: Props - ListItem Field", ExampleTier.Free, sw.ElapsedMilliseconds, "Item 'Active' not found. Run E115_ef first."); } var person = PersonEfMapping.ToEntity("John Doe", 30, "john@example.com", activeStatus._id, []); db.objects.Add(person); await db.SaveChangesAsync(); personId = person._id; } RedbObject? loaded; await using (var db = await contexts.CreateDbContextAsync()) { var entity = await db.Persons().FirstOrDefaultAsync(p => p._id == personId); loaded = entity == null ? null : PersonEfMapping.ToBusiness(entity); } sw.Stop(); var statusValue = loaded?.Props?.Status?.Value ?? "N/A"; return Ok("E118_ef", "EF: Props - ListItem Field", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Person ID: {personId}", $"Status: {statusValue}"]); } } Path: redb/redb.Examples/ExamplesEf/E119_PropsListItemArray_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E119_PropsListItemArray_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a person whose Roles point at the first three items, /// saved and loaded back whole with the items included. /// [ExampleMeta("E119_ef", "EF: Props - List", "List", ExampleTier.Free, 1, "EF", "List")] public class E119_PropsListItemArray_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); long personId; await using (var db = await contexts.CreateDbContextAsync()) { var list = await db.lists.FirstOrDefaultAsync(l => l._name == "ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E119_ef", "EF: Props - List", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114_ef first."); } var items = await db.list_items.Where(i => i._id_list == list._id).OrderBy(i => i._id).ToListAsync(); if (items.Count < 2) { sw.Stop(); return Fail("E119_ef", "EF: Props - List", ExampleTier.Free, sw.ElapsedMilliseconds, "Need at least 2 items. Run E115_ef first."); } var person = PersonEfMapping.ToEntity("Jane Smith", 28, "jane@example.com", null, items.Take(3).Select(i => i._id).ToList()); db.objects.Add(person); await db.SaveChangesAsync(); personId = person._id; } RedbObject? loaded; await using (var db = await contexts.CreateDbContextAsync()) { var entity = await db.Persons().FirstOrDefaultAsync(p => p._id == personId); loaded = entity == null ? null : PersonEfMapping.ToBusiness(entity); } sw.Stop(); var rolesCount = loaded?.Props?.Roles?.Count ?? 0; var rolesList = loaded?.Props?.Roles != null ? string.Join(", ", loaded.Props.Roles.Select(r => r.Value)) : "N/A"; return Ok("E119_ef", "EF: Props - List", ExampleTier.Free, sw.ElapsedMilliseconds, rolesCount, [$"Person ID: {personId}", $"Roles ({rolesCount}): {rolesList}"]); } } Path: redb/redb.Examples/ExamplesEf/E120_ListItemWhereByValue_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E120_ListItemWhereByValue_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : persons whose status item has the value "Active", whole. [ExampleMeta("E120_ef", "EF: ListItem - Where by Value", "List", ExampleTier.Free, 1, "EF", "List", "Where")] public class E120_ListItemWhereByValue_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var results = (await db.Persons() .Where(p => p.StatusNavigation!._value == "Active") .OrderBy(p => p._id) .Take(100) .ToListAsync()) .Select(PersonEfMapping.ToBusiness).ToList(); sw.Stop(); if (results.Count == 0) return Ok("E120_ef", "EF: ListItem - Where by Value", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["No persons with Status='Active' found", "Run E118_ef first to create test data"]); var firstName = results.FirstOrDefault()?.Props?.Name ?? "N/A"; return Ok("E120_ef", "EF: ListItem - Where by Value", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, ["Filter: Status.Value == 'Active'", $"Found: {results.Count}, First: {firstName}"]); } } Path: redb/redb.Examples/ExamplesEf/E121_ListItemWhereIn_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E121_ListItemWhereIn_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : persons whose status item value is one of three, whole. [ExampleMeta("E121_ef", "EF: ListItem - WhereIn by Value", "List", ExampleTier.Free, 1, "EF", "List", "WhereIn")] public class E121_ListItemWhereIn_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var targetValues = new[] { "Active", "Pending", "Blocked" }; var results = (await db.Persons() .Where(p => targetValues.Contains(p.StatusNavigation!._value)) .OrderBy(p => p._id) .Take(100) .ToListAsync()) .Select(PersonEfMapping.ToBusiness).ToList(); sw.Stop(); if (results.Count == 0) return Ok("E121_ef", "EF: ListItem - WhereIn by Value", ExampleTier.Free, sw.ElapsedMilliseconds, 0, [$"Filter: Status.Value IN [{string.Join(", ", targetValues)}]", "No matching persons found"]); var statuses = results.Select(r => r.Props?.Status?.Value ?? "N/A").Distinct(); return Ok("E121_ef", "EF: ListItem - WhereIn by Value", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Status.Value IN [{string.Join(", ", targetValues)}]", $"Found statuses: {string.Join(", ", statuses)}"]); } } Path: redb/redb.Examples/ExamplesEf/E122_ListItemDirectCompare_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E122_ListItemDirectCompare_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the "Active" item looked up, then persons whose Status is that item, whole. [ExampleMeta("E122_ef", "EF: ListItem - Direct Compare", "List", ExampleTier.Free, 1, "EF", "List", "Where")] public class E122_ListItemDirectCompare_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var list = await db.lists.FirstOrDefaultAsync(l => l._name == "ExampleStatuses"); if (list == null) { sw.Stop(); return Fail("E122_ef", "EF: ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds, "List 'ExampleStatuses' not found. Run E114_ef first."); } var items = await db.list_items.Where(i => i._id_list == list._id).ToListAsync(); var activeItem = items.FirstOrDefault(i => i._value == "Active"); if (activeItem == null) { sw.Stop(); return Fail("E122_ef", "EF: ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds, "Item 'Active' not found. Run E115_ef first."); } var results = (await db.Persons() .Where(p => p.Status == activeItem._id) .OrderBy(p => p._id) .Take(100) .ToListAsync()) .Select(PersonEfMapping.ToBusiness).ToList(); sw.Stop(); return Ok("E122_ef", "EF: ListItem - Direct Compare", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"Filter: Status == ListItem(ID:{activeItem._id})", $"Found: {results.Count} persons"]); } } Path: redb/redb.Examples/ExamplesEf/E123_ListItemArrayAny_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E123_ListItemArrayAny_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : persons with any role item valued "Active", whole. [ExampleMeta("E123_ef", "EF: ListItem Array - Any", "List", ExampleTier.Free, 1, "EF", "List", "Any")] public class E123_ListItemArrayAny_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var results = (await db.Persons() .Where(p => p.PersonProps_Roles.Any(r => r._valueNavigation!._value == "Active")) .OrderBy(p => p._id) .Take(100) .ToListAsync()) .Select(PersonEfMapping.ToBusiness).ToList(); sw.Stop(); if (results.Count == 0) return Ok("E123_ef", "EF: ListItem Array - Any", ExampleTier.Free, sw.ElapsedMilliseconds, 0, ["Filter: Roles.Any(r => r.Value == 'Active')", "No matching persons found. Run E119_ef first."]); var firstName = results.FirstOrDefault()?.Props?.Name ?? "N/A"; var rolesCount = results.FirstOrDefault()?.Props?.Roles?.Count ?? 0; return Ok("E123_ef", "EF: ListItem Array - Any", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, ["Filter: Roles.Any(r => r.Value == 'Active')", $"Found: {results.Count}, First: {firstName} ({rolesCount} roles)"]); } } Path: redb/redb.Examples/ExamplesEf/E124_SumAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E124_SumAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : SUM(Salary) and SUM(HomeAddress.Building.Floor) on the /// server; the nested floor costs EF two joins. [ExampleMeta("E124_ef", "EF: SumAsync - Total", "Analytics", ExampleTier.Free, 1, "EF", "Sum")] public class E124_SumAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var totalSalary = await db.EmployeeProps.SumAsync(e => e.Salary); var totalFloor = await db.EmployeeProps.SumAsync(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor); sw.Stop(); return Ok("E124_ef", "EF: SumAsync - Total", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [$"SUM(Salary) = {totalSalary:N0}", $"SUM(HomeAddress.Building.Floor) = {totalFloor:N0}", "Server-side aggregation"]); } } Path: redb/redb.Examples/ExamplesEf/E125_AverageAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E125_AverageAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : AVG(Age) and AVG(HomeAddress.Building.Floor) on the /// server; the nested floor costs EF two joins. [ExampleMeta("E125_ef", "EF: AverageAsync - Mean", "Analytics", ExampleTier.Free, 1, "EF")] public class E125_AverageAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var avgAge = await db.EmployeeProps.AverageAsync(e => e.Age); var avgFloor = await db.EmployeeProps.AverageAsync(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor); sw.Stop(); return Ok("E125_ef", "EF: AverageAsync - Mean", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [$"AVG(Age) = {avgAge:F2}", $"AVG(HomeAddress.Building.Floor) = {avgFloor:F2}", "Server-side aggregation"]); } } Path: redb/redb.Examples/ExamplesEf/E126_MinMaxAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E126_MinMaxAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : MIN and MAX of Salary and of /// HomeAddress.Building.Floor, four queries as in redb; the nested floor costs EF two joins. [ExampleMeta("E126_ef", "EF: MinAsync/MaxAsync - Range", "Analytics", ExampleTier.Free, 1, "EF")] public class E126_MinMaxAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var minSalary = await db.EmployeeProps.MinAsync(e => e.Salary); var maxSalary = await db.EmployeeProps.MaxAsync(e => e.Salary); var minFloor = await db.EmployeeProps.MinAsync(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor); var maxFloor = await db.EmployeeProps.MaxAsync(e => e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor); sw.Stop(); return Ok("E126_ef", "EF: MinAsync/MaxAsync - Range", ExampleTier.Free, sw.ElapsedMilliseconds, 4, [$"MIN(Salary) = {minSalary:N0}", $"MAX(Salary) = {maxSalary:N0}", $"MIN/MAX(HomeAddress.Building.Floor) = {minFloor}..{maxFloor}"]); } } Path: redb/redb.Examples/ExamplesEf/E127_AggregateAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E127_AggregateAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : eight aggregates in one query. EF has no batch aggregate /// API; the usual way is to group the whole set by a constant. The nested floor is reached through the /// navigations EmployeeProps -> HomeAddress -> Building, which EF turns into two joins (Include plays no part /// in an aggregate). /// [ExampleMeta("E127_ef", "EF: AggregateAsync - Batch", "Analytics", ExampleTier.Free, 1, "EF")] public class E127_AggregateAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var stats = await db.EmployeeProps .Select(e => new { e.Salary, e.Age, Floor = e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor }) .GroupBy(_ => 1) .Select(g => new { TotalSalary = g.Sum(x => x.Salary), AvgAge = g.Average(x => x.Age), MinSalary = g.Min(x => x.Salary), MaxSalary = g.Max(x => x.Salary), MinFloor = g.Min(x => x.Floor), MaxFloor = g.Max(x => x.Floor), AvgFloor = g.Average(x => x.Floor), Count = g.Count() }) .FirstAsync(); sw.Stop(); return Ok("E127_ef", "EF: AggregateAsync - Batch", ExampleTier.Free, sw.ElapsedMilliseconds, stats.Count, ["8 aggregations in 1 query, 3 of them over HomeAddress.Building.Floor", $"Total: {stats.TotalSalary:N0}, Avg Age: {stats.AvgAge:F1}, Count: {stats.Count}", $"Home floor: {stats.MinFloor}..{stats.MaxFloor}, avg {stats.AvgFloor:F1}"]); } } Path: redb/redb.Examples/ExamplesEf/E128_GroupBySimple_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E128_GroupBySimple_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : per department total salary, average age, average /// HomeAddress.Building.Floor and count; the nested floor costs EF two joins. [ExampleMeta("E128_ef", "EF: GroupBy - Simple", "Analytics", ExampleTier.Free, 1, "EF", "GroupBy")] public class E128_GroupBySimple_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var byDept = await db.EmployeeProps .Select(e => new { e.Department, e.Salary, e.Age, Floor = e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor }) .GroupBy(x => x.Department) .Select(g => new { Department = g.Key, TotalSalary = g.Sum(x => x.Salary), AvgAge = g.Average(x => x.Age), AvgFloor = g.Average(x => x.Floor), Count = g.Count() }) .ToListAsync(); sw.Stop(); var first = byDept.FirstOrDefault(); return Ok("E128_ef", "EF: GroupBy - Simple", ExampleTier.Free, sw.ElapsedMilliseconds, byDept.Count, [$"Groups: {byDept.Count}", $"First: {first?.Department ?? "N/A"}, Count: {first?.Count ?? 0}, Avg home floor: {first?.AvgFloor:F2}"]); } } Path: redb/redb.Examples/ExamplesEf/E129_GroupByFiltered_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E129_GroupByFiltered_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Salary above 50000, grouped by department, with the /// highest HomeAddress.Building.Floor per group; the nested floor costs EF two joins. [ExampleMeta("E129_ef", "EF: GroupBy - With Filter", "Analytics", ExampleTier.Free, 1, "EF")] public class E129_GroupByFiltered_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var byDeptFiltered = await db.EmployeeProps .Where(x => x.Salary > 50000m) .Select(e => new { e.Department, e.Salary, Floor = e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor }) .GroupBy(x => x.Department) .Select(g => new { Department = g.Key, TotalSalary = g.Sum(x => x.Salary), MaxFloor = g.Max(x => x.Floor), Count = g.Count() }) .ToListAsync(); sw.Stop(); var first = byDeptFiltered.FirstOrDefault(); return Ok("E129_ef", "EF: GroupBy - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, byDeptFiltered.Count, ["Filter: Salary > 50k", $"Groups: {byDeptFiltered.Count}, First: {first?.Department ?? "N/A"}, Max home floor: {first?.MaxFloor}"]); } } Path: redb/redb.Examples/ExamplesEf/E130_GroupByMultiKey_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E130_GroupByMultiKey_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : grouped by department and position, with the average /// HomeAddress.Building.Floor per group; the nested floor costs EF two joins. [ExampleMeta("E130a_ef", "EF: GroupBy - Composite Key", "Analytics", ExampleTier.Free, 1, "EF")] public class E130_GroupByMultiKey_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var byDeptPosition = await db.EmployeeProps .Select(e => new { e.Department, e.Position, e.Salary, Floor = e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor }) .GroupBy(x => new { x.Department, x.Position }) .Select(g => new { g.Key.Department, g.Key.Position, TotalSalary = g.Sum(x => x.Salary), AvgFloor = g.Average(x => x.Floor), Count = g.Count() }) .ToListAsync(); sw.Stop(); var first = byDeptPosition.FirstOrDefault(); return Ok("E130a_ef", "EF: GroupBy - Composite Key", ExampleTier.Free, sw.ElapsedMilliseconds, byDeptPosition.Count, [$"Groups: {byDeptPosition.Count}", $"First: {first?.Department ?? "N/A"}/{first?.Position ?? "N/A"}, Avg home floor: {first?.AvgFloor:F2}"]); } } Path: redb/redb.Examples/ExamplesEf/E131_GroupByRedb_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E131_GroupByRedb_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : total salary and count per owner. The owner is a field of /// the shared objects header, reached through the navigation from the employee. /// [ExampleMeta("E131_ef", "EF: GroupByRedb - Base Fields", "Analytics", ExampleTier.Free, 1, "EF", "GroupBy")] public class E131_GroupByRedb_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var byOwner = await db.EmployeeProps .Select(e => new { e.objects._id_owner, e.Salary, Floor = e.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor }) .GroupBy(e => e._id_owner) .Select(g => new { OwnerId = g.Key, TotalSalary = g.Sum(e => e.Salary), AvgFloor = g.Average(e => e.Floor), Count = g.Count() }) .ToListAsync(); sw.Stop(); var first = byOwner.FirstOrDefault(); return Ok("E131_ef", "EF: GroupByRedb - Base Fields", ExampleTier.Free, sw.ElapsedMilliseconds, byOwner.Count, ["SQL: GROUP BY objects._id_owner (join to the header)", $"Groups: {byOwner.Count}, First owner: {first?.OwnerId ?? 0}", $"Avg home floor of the first owner: {first?.AvgFloor:F2}"]); } } Path: redb/redb.Examples/ExamplesEf/E132_WindowRowNumber_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E132_WindowRowNumber_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . EF Core does not translate window functions /// (ROW_NUMBER() OVER (PARTITION BY ...)): dotnet/efcore#12747 is open since 2018 and absent from the /// EF Core 10 release notes. Doing it anyway takes raw SQL or a third-party package, neither of which is /// EF out of the box. /// [ExampleMeta("E132_ef", "EF: Window - RowNumber", "Analytics", ExampleTier.Free, 1, "EF", "Window")] public class E132_WindowRowNumber_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E132_ef", "EF: Window - RowNumber", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E133_WindowRunningSum_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E133_WindowRunningSum_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . EF Core does not translate window functions (dotnet/efcore#12747), open since 2018 and absent from the EF Core 10 release notes. Doing it anyway takes raw SQL or a third-party package, neither of which is EF out of the box. /// [ExampleMeta("E133_ef", "EF: Window - Running Sum", "Analytics", ExampleTier.Free, 1, "EF")] public class E133_WindowRunningSum_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E133_ef", "EF: Window - Running Sum", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E134_WindowLagLead_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E134_WindowLagLead_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . EF Core does not translate window functions (dotnet/efcore#12747), open since 2018 and absent from the EF Core 10 release notes. Doing it anyway takes raw SQL or a third-party package, neither of which is EF out of the box. /// [ExampleMeta("E134_ef", "EF: Window - Lag/Lead", "Analytics", ExampleTier.Free, 1, "EF")] public class E134_WindowLagLead_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E134_ef", "EF: Window - Lag/Lead", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E135_WindowRank_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E135_WindowRank_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . EF Core does not translate window functions (dotnet/efcore#12747), open since 2018 and absent from the EF Core 10 release notes. Doing it anyway takes raw SQL or a third-party package, neither of which is EF out of the box. /// [ExampleMeta("E135_ef", "EF: Window - Rank/DenseRank", "Analytics", ExampleTier.Free, 1, "EF")] public class E135_WindowRank_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E135_ef", "EF: Window - Rank/DenseRank", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E136_WindowNtile_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E136_WindowNtile_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . EF Core does not translate window functions (dotnet/efcore#12747), open since 2018 and absent from the EF Core 10 release notes. Doing it anyway takes raw SQL or a third-party package, neither of which is EF out of the box. /// [ExampleMeta("E136_ef", "EF: Window - Ntile", "Analytics", ExampleTier.Free, 1, "EF")] public class E136_WindowNtile_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E136_ef", "EF: Window - Ntile", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E137_WindowFirstLast_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E137_WindowFirstLast_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . EF Core does not translate window functions (dotnet/efcore#12747), open since 2018 and absent from the EF Core 10 release notes. Doing it anyway takes raw SQL or a third-party package, neither of which is EF out of the box. /// [ExampleMeta("E137_ef", "EF: Window - FirstValue/LastValue", "Analytics", ExampleTier.Free, 1, "EF")] public class E137_WindowFirstLast_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E137_ef", "EF: Window - FirstValue/LastValue", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E138_WindowFrame_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E138_WindowFrame_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of . EF Core does not translate window functions (dotnet/efcore#12747), open since 2018 and absent from the EF Core 10 release notes. Doing it anyway takes raw SQL or a third-party package, neither of which is EF out of the box. /// [ExampleMeta("E138_ef", "EF: Window - Frame (Sliding)", "Analytics", ExampleTier.Free, 1, "EF")] public class E138_WindowFrame_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E138_ef", "EF: Window - Frame (Sliding)", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E139_DistinctRedb_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E139_DistinctRedb_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : up to 100 employees unique by every header field except /// the key, as whole objects. EF has no DISTINCT ON; its usual way is to group by those fields, keep the /// smallest key of each group, then load the objects by those keys. /// [ExampleMeta("E139_ef", "EF: DistinctRedb - Find Duplicates", "Analytics", ExampleTier.Pro, 1, "EF", "Distinct")] public class E139_DistinctRedb_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var ids = await db.EmployeeProps .GroupBy(e => new { e.objects._id_parent, e.objects._id_scheme, e.objects._id_owner, e.objects._id_who_change, e.objects._date_create, e.objects._date_modify, e.objects._date_begin, e.objects._date_complete, e.objects._key, e.objects._name, e.objects._note, e.objects._value_long, e.objects._value_string, e.objects._value_guid, e.objects._value_bool, e.objects._value_double, e.objects._value_numeric, e.objects._value_datetime, e.objects._value_bytes }) .Select(g => g.Min(e => e._id)) .OrderBy(id => id) .Take(100) .ToListAsync(); var unique = await db.EmployeeProps.WithGraph() .Where(e => ids.Contains(e._id)) .ToBusinessListAsync(); sw.Stop(); return Ok("E139_ef", "EF: DistinctRedb - Find Duplicates", ExampleTier.Pro, sw.ElapsedMilliseconds, unique.Count, ["GROUP BY header fields except _id, then load by key", $"Unique: {unique.Count} objects"]); } } Path: redb/redb.Examples/ExamplesEf/E140_DistinctByRedb_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E140_DistinctByRedb_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : up to 100 employees with distinct names, as whole objects. /// EF has no DISTINCT ON; it groups by the name, keeps the smallest key of each group and loads by those keys. /// [ExampleMeta("E140_ef", "EF: DistinctByRedb - By Field", "Analytics", ExampleTier.Pro, 1, "EF", "Distinct")] public class E140_DistinctByRedb_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var ids = await db.EmployeeProps .GroupBy(e => e.objects._name) .Select(g => g.Min(e => e._id)) .OrderBy(id => id) .Take(100) .ToListAsync(); var uniqueByName = await db.EmployeeProps.WithGraph() .Where(e => ids.Contains(e._id)) .ToBusinessListAsync(); sw.Stop(); var names = string.Join(", ", uniqueByName.Take(3).Select(x => x.name)); return Ok("E140_ef", "EF: DistinctByRedb - By Field", ExampleTier.Pro, sw.ElapsedMilliseconds, uniqueByName.Count, ["GROUP BY objects._name, then load by key", $"First 3: {names}..."]); } } Path: redb/redb.Examples/ExamplesEf/E141_WhereInRedb_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E141_WhereInRedb_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : five keys, then the employees with those keys as whole objects. [ExampleMeta("E141_ef", "EF: WhereInRedb - Base Field", "Analytics", ExampleTier.Free, 1, "EF", "WhereIn")] public class E141_WhereInRedb_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var sampleIds = await db.EmployeeProps.Select(e => e._id).Take(5).ToListAsync(); if (sampleIds.Count == 0) { sw.Stop(); return Fail("E141_ef", "EF: WhereInRedb - Base Field", ExampleTier.Free, sw.ElapsedMilliseconds, "No employees found. Run E203_ef first."); } var results = await db.EmployeeProps.WithGraph() .Where(e => sampleIds.Contains(e._id)) .ToBusinessListAsync(); sw.Stop(); return Ok("E141_ef", "EF: WhereInRedb - Base Field", ExampleTier.Free, sw.ElapsedMilliseconds, results.Count, [$"WHERE _id IN ({string.Join(",", sampleIds.Take(3))}...)", $"Found: {results.Count}"]); } } Path: redb/redb.Examples/ExamplesEf/E142_GroupByArray_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E142_GroupByArray_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the metadata entries of the contacts of employees living /// above the 10th floor, grouped by label. The depth costs EF joins from the metadata table through the contact, the /// employee, its address and building. EF Core does not translate window functions (dotnet/efcore#12747), so the /// RANK over the groups is computed in memory from the grouped rows. [ExampleMeta("E142_ef", "EF: GroupByArray - Nested Array Elements", "Analytics", ExampleTier.Free, 1, "EF", "GroupBy")] public class E142_GroupByArray_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var query = db.EmployeeProps_Contacts_Metadata .Where(m => m._owner._owner.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor > 10) .GroupBy(m => m.Label) .Select(g => new { Label = g.Key, Entries = g.Count(), CorporateDomain = g.Count(m => m.Value == "company.com") }); var groups = await query.ToListAsync(); var ranked = groups .Select(g => new { g.Label, g.Entries, g.CorporateDomain, Rank = 1 + groups.Count(o => o.Entries > g.Entries) }) .ToList(); sw.Stop(); var output = ranked.OrderBy(g => g.Rank).ThenBy(g => g.Label) .Select(g => $"#{g.Rank} {g.Label}: {g.Entries} entries, {g.CorporateDomain} with value company.com") .Prepend($"Groups by Contacts[].Metadata[].Label, home floor > 10: {ranked.Count}") .Append("SQL:") .Concat(query.ToQueryString().Split('\n').Select(l => l.TrimEnd('\r'))) .ToArray(); return Ok("E142_ef", "EF: GroupByArray - Nested Array Elements", ExampleTier.Free, sw.ElapsedMilliseconds, ranked.Count, output); } } Path: redb/redb.Examples/ExamplesEf/E143_SumRedbAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E143_SumRedbAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : SUM of the employee keys and the count, two queries. [ExampleMeta("E143_ef", "EF: SumRedbAsync - Base Field Sum", "Analytics", ExampleTier.Free, 1, "EF", "Sum")] public class E143_SumRedbAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var sumId = await db.EmployeeProps.SumAsync(e => e._id); var count = await db.EmployeeProps.CountAsync(); sw.Stop(); return Ok("E143_ef", "EF: SumRedbAsync - Base Field Sum", ExampleTier.Free, sw.ElapsedMilliseconds, count, [$"SUM(_id) = {sumId:N0}", $"Count: {count}"]); } } Path: redb/redb.Examples/ExamplesEf/E144_MinMaxRedbAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E144_MinMaxRedbAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : first and last creation date of the employees, two /// queries; the date is a field of the objects header. /// [ExampleMeta("E144_ef", "EF: Min/MaxRedbAsync - Date Range", "Analytics", ExampleTier.Free, 1, "EF", "Min", "Max")] public class E144_MinMaxRedbAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var minDate = await db.EmployeeProps.MinAsync(e => (DateTime?)e.objects._date_create); var maxDate = await db.EmployeeProps.MaxAsync(e => (DateTime?)e.objects._date_create); sw.Stop(); var range = minDate.HasValue && maxDate.HasValue ? (maxDate.Value - minDate.Value).Days : 0; return Ok("E144_ef", "EF: Min/MaxRedbAsync - Date Range", ExampleTier.Free, sw.ElapsedMilliseconds, 2, [$"First: {minDate?.ToString("yyyy-MM-dd") ?? "N/A"}", $"Last: {maxDate?.ToString("yyyy-MM-dd") ?? "N/A"}", $"Range: {range} days"]); } } Path: redb/redb.Examples/ExamplesEf/E145_AverageRedbAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E145_AverageRedbAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : AVG, MIN and MAX of the employee keys, three queries as in redb. [ExampleMeta("E145_ef", "EF: AverageRedbAsync - Base Field Avg", "Analytics", ExampleTier.Free, 1, "EF", "Average")] public class E145_AverageRedbAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var avgId = await db.EmployeeProps.AverageAsync(e => e._id); var minId = await db.EmployeeProps.MinAsync(e => (long?)e._id); var maxId = await db.EmployeeProps.MaxAsync(e => (long?)e._id); sw.Stop(); return Ok("E145_ef", "EF: AverageRedbAsync - Base Field Avg", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"AVG(_id) = {avgId:F2}", $"Range: {minId?.ToString() ?? "N/A"} - {maxId?.ToString() ?? "N/A"}"]); } } Path: redb/redb.Examples/ExamplesEf/E146_AggregateRedbAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E146_AggregateRedbAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : five aggregates over header fields in one query, /// grouping the whole set by a constant; the dates come from the objects header. /// [ExampleMeta("E146_ef", "EF: AggregateRedbAsync - Batch Base", "Analytics", ExampleTier.Free, 1, "EF", "Aggregate")] public class E146_AggregateRedbAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var stats = await db.EmployeeProps .Select(e => new { e._id, e.objects._date_create, e.objects._date_modify }) .GroupBy(_ => 1) .Select(g => new { MaxId = g.Max(x => x._id), MinDateCreate = g.Min(x => x._date_create), MaxDateModify = g.Max(x => x._date_modify), AvgId = g.Average(x => x._id), Count = g.Count() }) .FirstAsync(); sw.Stop(); return Ok("E146_ef", "EF: AggregateRedbAsync - Batch Base", ExampleTier.Free, sw.ElapsedMilliseconds, stats.Count, ["5 aggregations in 1 query (join to the header)", $"MaxId: {stats.MaxId}, Count: {stats.Count}", $"Dates: {stats.MinDateCreate:yyyy-MM-dd} - {stats.MaxDateModify:yyyy-MM-dd}"]); } } Path: redb/redb.Examples/ExamplesEf/E147_WindowPartitionByRedb_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E147_WindowPartitionByRedb_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : ROW_NUMBER over a partition, which EF Core cannot express. [ExampleMeta("E147_ef", "EF: Window - PartitionByRedb", "Analytics", ExampleTier.Free, 1, "EF", "Window")] public class E147_WindowPartitionByRedb_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E147_ef", "EF: Window - PartitionByRedb", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E148_WindowOrderByRedb_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E148_WindowOrderByRedb_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a running COUNT over a window frame, which EF Core cannot express. [ExampleMeta("E148_ef", "EF: Window - OrderByRedb", "Analytics", ExampleTier.Free, 1, "EF", "Window")] public class E148_WindowOrderByRedb_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E148_ef", "EF: Window - OrderByRedb", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E149_SelectProjection_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E149_SelectProjection_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : three fields of 100 employees, then the same 100 as /// whole objects. As in redb, the measured time covers both. /// [ExampleMeta("E149_ef", "EF: Select - Projection", "Query", ExampleTier.Free, 1, "EF")] public class E149_SelectProjection_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var projected = await db.EmployeeProps .Take(100) .Select(x => new { x._id, x.FirstName, x.Salary, HomeCity = x.EmployeeProps_HomeAddress!.City, HomeFloor = x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor }) .ToListAsync(); // OrderBy(_id) is EF's own need: with split queries and Take, every child query must pick the same rows. var swFull = Stopwatch.StartNew(); var full = await db.EmployeeProps.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); swFull.Stop(); sw.Stop(); var first = projected.FirstOrDefault(); return Ok("E149_ef", "EF: Select - Projection", ExampleTier.Free, sw.ElapsedMilliseconds, projected.Count, [$"Projected 5 fields, 2 of them nested: {sw.ElapsedMilliseconds - swFull.ElapsedMilliseconds}ms", $"Full load: {swFull.ElapsedMilliseconds}ms ({full.Count} objects)", first != null ? $"First: {first.FirstName} ${first.Salary:N0}, home {first.HomeCity}, floor {first.HomeFloor}" : "No data"]); } } Path: redb/redb.Examples/ExamplesEf/E150A_ArrayAggregationByIndex_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E150A_ArrayAggregationByIndex_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : SUM and AVG of SkillLevels[0], one query over the array table. [ExampleMeta("E150A_ef", "EF: Array Aggregation - By Index", "Analytics", ExampleTier.Free, 1, "EF", "Array", "Aggregation")] public class E150A_ArrayAggregationByIndex_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var firstElement = await db.EmployeeProps_SkillLevels .Where(s => s._idx == 0) .GroupBy(_ => 1) .Select(g => new { SumFirstSkill = g.Sum(s => s._value), AvgFirstSkill = g.Average(s => s._value) }) .FirstAsync(); sw.Stop(); return Ok("E150A_ef", "EF: Array Aggregation - By Index", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"SkillLevels[0]: Sum={firstElement.SumFirstSkill}, Avg={firstElement.AvgFirstSkill:F2}"]); } } Path: redb/redb.Examples/ExamplesEf/E150_ArrayAggregation_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E150_ArrayAggregation_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : SUM and AVG over every element of SkillLevels and the /// employee count. The elements and the employees are two tables, so EF asks twice; redb asks once. /// [ExampleMeta("E150_ef", "EF: Array Aggregation - All Elements", "Analytics", ExampleTier.Free, 1, "EF", "Array", "Aggregation")] public class E150_ArrayAggregation_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var allElements = await db.EmployeeProps_SkillLevels .GroupBy(_ => 1) .Select(g => new { TotalSkillPoints = g.Sum(s => s._value), AvgSkillLevel = g.Average(s => s._value) }) .FirstAsync(); var count = await db.EmployeeProps.CountAsync(); sw.Stop(); return Ok("E150_ef", "EF: Array Aggregation - All Elements", ExampleTier.Free, sw.ElapsedMilliseconds, count, [$"All SkillLevels[]: Sum={allElements.TotalSkillPoints}, Avg={allElements.AvgSkillLevel:F2}", $"Employees: {count}"]); } } Path: redb/redb.Examples/ExamplesEf/E151_ArithmeticMultiply_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E151_ArithmeticMultiply_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Salary * 12 above 1 000 000, up to 100 whole objects and the count. [ExampleMeta("E151_ef", "EF: Where - Arithmetic Multiply", "Query", ExampleTier.Pro, 1, "EF", "Where", "Arithmetic")] public class E151_ArithmeticMultiply_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.Salary * 12 > 1_000_000m); var highEarners = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var first = highEarners.FirstOrDefault(); var annualSalary = first?.Props.Salary * 12 ?? 0; return Ok("E151_ef", "EF: Where - Arithmetic Multiply", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Filter: Salary * 12 > 1,000,000", $"Found: {totalCount} high earners", $"First: {first?.Props.FirstName} {first?.Props.LastName}, Annual: ${annualSalary:N0}"]); } } Path: redb/redb.Examples/ExamplesEf/E152_ArithmeticAddFields_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E152_ArithmeticAddFields_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Age * 1000 + Salary above 120 000, up to 100 whole objects and the count. [ExampleMeta("E152_ef", "EF: Where - Arithmetic Add Fields", "Query", ExampleTier.Pro, 1, "EF", "Where", "Arithmetic")] public class E152_ArithmeticAddFields_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.Age * 1000 + e.Salary > 120_000m); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var first = results.FirstOrDefault(); var score = first != null ? first.Props.Age * 1000 + (int)first.Props.Salary : 0; return Ok("E152_ef", "EF: Where - Arithmetic Add Fields", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Formula: Age * 1000 + Salary > 120,000", $"Found: {totalCount} employees", $"First: {first?.Props.FirstName}, Age {first?.Props.Age}, Score: {score:N0}"]); } } Path: redb/redb.Examples/ExamplesEf/E153_StringToLower_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E153_StringToLower_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : LastName.ToLower() contains "s", up to 100 whole objects and the count. [ExampleMeta("E153_ef", "EF: Where - String ToLower", "Query", ExampleTier.Pro, 1, "EF", "Where", "String")] public class E153_StringToLower_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.LastName!.ToLower().Contains("s")); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var names = results.Take(3).Select(e => e.Props.LastName); return Ok("E153_ef", "EF: Where - String ToLower", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Filter: LastName.ToLower().Contains(\"s\")", $"Found: {totalCount} employees", $"Examples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/ExamplesEf/E154_StringTrim_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E154_StringTrim_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : FirstName.Trim().Length above 3, up to 100 whole objects and the count. [ExampleMeta("E154_ef", "EF: Where - String Trim", "Query", ExampleTier.Pro, 1, "EF", "Where", "String")] public class E154_StringTrim_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.FirstName!.Trim().Length > 3); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var names = results.Take(5).Select(e => $"{e.Props.FirstName} ({e.Props.FirstName.Length} chars)"); return Ok("E154_ef", "EF: Where - String Trim", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Filter: FirstName.Trim().Length > 3", $"Found: {totalCount} employees", $"Examples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/ExamplesEf/E155_StringChain_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E155_StringChain_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Department.ToUpper().Length above 5, up to 100 whole objects and the count. [ExampleMeta("E155_ef", "EF: Where - String Chain", "Query", ExampleTier.Pro, 1, "EF", "Where", "String")] public class E155_StringChain_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.Department!.ToUpper().Length > 5); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var depts = results.Select(e => e.Props.Department).Distinct().Take(5); return Ok("E155_ef", "EF: Where - String Chain", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Filter: Department.ToUpper().Length > 5", $"Found: {totalCount} employees", $"Departments: {string.Join(", ", depts)}"]); } } Path: redb/redb.Examples/ExamplesEf/E156_MathAbs_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E156_MathAbs_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : |Age - 35| at most 5, up to 100 whole objects and the count. [ExampleMeta("E156_ef", "EF: Where - Math.Abs", "Query", ExampleTier.Pro, 1, "EF", "Where", "Math")] public class E156_MathAbs_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => Math.Abs(e.Age!.Value - 35) <= 5); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var ages = results.Take(5).Select(e => e.Props.Age); var avgAge = results.Any() ? results.Average(e => e.Props.Age) : 0; return Ok("E156_ef", "EF: Where - Math.Abs", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Filter: |Age - 35| <= 5 (ages 30-40)", $"Found: {totalCount} employees", $"Ages: {string.Join(", ", ages)}, Avg: {avgAge:F1}"]); } } Path: redb/redb.Examples/ExamplesEf/E157_DateTimeYear_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E157_DateTimeYear_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : objects created this year and older than 30, up to 100 whole /// objects, and the count of this year's objects. The creation date is a field of the objects header. /// [ExampleMeta("E157_ef", "EF: WhereRedb - DateTime.Year", "Query", ExampleTier.Pro, 1, "EF", "Where", "DateTime")] public class E157_DateTimeYear_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var currentYear = DateTime.UtcNow.Year; var thisYear = db.EmployeeProps.Where(e => e.objects._date_create.Year == currentYear); var results = await thisYear.Where(e => e.Age > 30) .WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await thisYear.CountAsync(); sw.Stop(); var dates = results.Take(3).Select(e => e.date_create.ToString("yyyy-MM-dd")); return Ok("E157_ef", "EF: WhereRedb - DateTime.Year", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, [$"Filter: DateCreate.Year == {currentYear}", $"Found: {totalCount} objects created this year", $"Dates: {string.Join(", ", dates)}"]); } } Path: redb/redb.Examples/ExamplesEf/E158_Parentheses_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E158_Parentheses_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : (Salary / 12) above 7000, up to 100 whole objects and the count. [ExampleMeta("E158_ef", "EF: Where - Parentheses Priority", "Query", ExampleTier.Pro, 1, "EF", "Where", "Arithmetic")] public class E158_Parentheses_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => (e.Salary / 12m) > 7000m); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var first = results.FirstOrDefault(); var monthly = first?.Props.Salary / 12m ?? 0; return Ok("E158_ef", "EF: Where - Parentheses Priority", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Filter: (Salary / 12) > 7,000 (monthly)", $"Found: {totalCount} employees", $"First: {first?.Props.FirstName}, Monthly: ${monthly:N0}"]); } } Path: redb/redb.Examples/ExamplesEf/E159_NestedMath_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E159_NestedMath_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : |Salary - 80000| below 10000, up to 100 whole objects and the count. [ExampleMeta("E159_ef", "EF: Where - Nested Math", "Query", ExampleTier.Pro, 1, "EF", "Where", "Math")] public class E159_NestedMath_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => Math.Abs(e.Salary!.Value - 80000m) < 10000m); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var salaries = results.Take(5).Select(e => $"${e.Props.Salary:N0}"); return Ok("E159_ef", "EF: Where - Nested Math", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["Filter: |Salary - 80k| < 10k ($70k-$90k range)", $"Found: {totalCount} employees", $"Salaries: {string.Join(", ", salaries)}"]); } } Path: redb/redb.Examples/ExamplesEf/E160_TreeQueryExpressions_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E160_TreeQueryExpressions_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a filter over the whole subtree of a root. [ExampleMeta("E160_ef", "EF: TreeQuery - Expressions", "Tree", ExampleTier.Free, 1, "EF", "Tree")] public class E160_TreeQueryExpressions_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E160_ef", "EF: TreeQuery - Expressions", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E161_SqlFunctionCoalesce_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E161_SqlFunctionCoalesce_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : COALESCE(Age, 0) above 30, up to 100 whole objects and /// the count. EF writes COALESCE for the C# ?? operator. /// [ExampleMeta("E161_ef", "EF: Sql.Function - COALESCE", "Query", ExampleTier.Pro, 1, "EF", "Where", "Function")] public class E161_SqlFunctionCoalesce_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => (e.Age ?? 0) > 30); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var ages = results.Take(5).Select(e => e.Props.Age); return Ok("E161_ef", "EF: Sql.Function - COALESCE", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["SQL: COALESCE(Age, 0) > 30", $"Found: {totalCount} employees", $"Ages: {string.Join(", ", ages)}"]); } } Path: redb/redb.Examples/ExamplesEf/E162_SqlFunctionPower_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E162_SqlFunctionPower_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : POWER(Age, 2) above 900, up to 100 whole objects and the /// count. EF writes POWER for Math.Pow. /// [ExampleMeta("E162_ef", "EF: Sql.Function - POWER", "Query", ExampleTier.Pro, 1, "EF", "Where", "Function")] public class E162_SqlFunctionPower_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => Math.Pow(e.Age!.Value, 2) > 900); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var ages = results.Take(5).Select(e => $"{e.Props.Age} (^2={e.Props.Age * e.Props.Age})"); return Ok("E162_ef", "EF: Sql.Function - POWER", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["SQL: POWER(Age, 2) > 900 (Age > 30)", $"Found: {totalCount} employees", $"Ages: {string.Join(", ", ages)}"]); } } Path: redb/redb.Examples/ExamplesEf/E163_SqlFunctionNested_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E163_SqlFunctionNested_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : SQRT(Salary) above 250, up to 100 whole objects and the /// count. EF writes sqrt for Math.Sqrt. /// [ExampleMeta("E163_ef", "EF: Sql.Function - Nested", "Query", ExampleTier.Pro, 1, "EF", "Where", "Function")] public class E163_SqlFunctionNested_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => Math.Sqrt((double)e.Salary!.Value) > 250); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var salaries = results.Take(5).Select(e => $"${e.Props.Salary:N0} (sqrt={Math.Sqrt((double)e.Props.Salary):F0})"); return Ok("E163_ef", "EF: Sql.Function - Nested", ExampleTier.Pro, sw.ElapsedMilliseconds, totalCount, ["SQL: SQRT(Salary) > 250 (Salary > 62,500)", $"Found: {totalCount} employees", $"Salaries: {string.Join(", ", salaries)}"]); } } Path: redb/redb.Examples/ExamplesEf/E164_BaseFieldsSingle_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E164_BaseFieldsSingle_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : one header row with value fields and no Props, saved and loaded back. [ExampleMeta("E164_ef", "EF: Base Fields - Single Object", "Core", ExampleTier.Free, 1, "EF", "Base")] public class E164_BaseFieldsSingle_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var now = DateTime.UtcNow; var obj = new objects { _id_scheme = EfSchemeIds.None, _date_create = now, _date_modify = now, _name = $"BaseFields_Example_{now.Ticks}", _value_string = "Example String Value", _value_long = 12345, _value_bool = true, _value_double = 3.14159, _value_datetime = now, _value_numeric = 99.99m }; await using (var db = await contexts.CreateDbContextAsync()) { db.objects.Add(obj); await db.SaveChangesAsync(); } var id = obj._id; objects? loaded; await using (var db = await contexts.CreateDbContextAsync()) loaded = await db.objects.FirstOrDefaultAsync(o => o._id == id); sw.Stop(); if (loaded == null) return Fail("E164_ef", "EF: Base Fields - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to load saved object."); var result = Ok("E164_ef", "EF: Base Fields - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"ID: {id}, Name: {loaded._name}", $"value_string: {loaded._value_string}", $"value_long: {loaded._value_long}, value_bool: {loaded._value_bool}"]); await using (var db = await contexts.CreateDbContextAsync()) await db.objects.Where(o => o._id == id).ExecuteDeleteAsync(); return result; } } Path: redb/redb.Examples/ExamplesEf/E165_BaseFieldsBatch_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E165_BaseFieldsBatch_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : ten header rows without Props, saved and loaded as a batch. [ExampleMeta("E165_ef", "EF: Base Fields - Batch Operations", "Core", ExampleTier.Free, 1, "EF", "Base", "Batch")] public class E165_BaseFieldsBatch_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var now = DateTime.UtcNow; var batch = Enumerable.Range(0, 1000).Select(i => new objects { _id_scheme = EfSchemeIds.None, _date_create = now, _date_modify = now, _name = $"Batch_BaseFields_{now.Ticks}_{i}", _value_string = $"Item_{i}", _value_long = i * 100, _value_bool = i % 2 == 0 }).ToList(); await using (var db = await contexts.CreateDbContextAsync()) { db.objects.AddRange(batch); await db.SaveChangesAsync(); } var ids = batch.Select(o => o._id).ToList(); List loaded; await using (var db = await contexts.CreateDbContextAsync()) loaded = await db.objects.Where(o => ids.Contains(o._id)).ToListAsync(); sw.Stop(); if (loaded.Count != 1000) return Fail("E165_ef", "EF: Base Fields - Batch Operations", ExampleTier.Free, sw.ElapsedMilliseconds, $"Expected 1000 objects, got {loaded.Count}."); var verified = loaded.All(x => x._value_string != null && x._value_string.StartsWith("Item_")); var result = Ok("E165_ef", "EF: Base Fields - Batch Operations", ExampleTier.Free, sw.ElapsedMilliseconds, loaded.Count, [$"Saved and loaded: {loaded.Count} objects", $"IDs: [{string.Join(", ", ids.Take(3))}...]", $"Data verified: {verified}"]); await using (var db = await contexts.CreateDbContextAsync()) await db.objects.Where(o => ids.Contains(o._id)).ExecuteDeleteAsync(); return result; } } Path: redb/redb.Examples/ExamplesEf/E166_GenericNullProps_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E166_GenericNullProps_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a header row marked as an employee but without an /// EmployeeProps row, saved and loaded back. /// [ExampleMeta("E166_ef", "EF: Generic with Props=null", "Core", ExampleTier.Free, 1, "EF", "Base")] public class E166_GenericNullProps_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var now = DateTime.UtcNow; var obj = new objects { _id_scheme = EfSchemeIds.Employee, _date_create = now, _date_modify = now, _name = $"GenericNullProps_{now.Ticks}", _value_string = "MetadataOnly", _value_long = 999, _value_bool = true }; await using (var db = await contexts.CreateDbContextAsync()) { db.objects.Add(obj); await db.SaveChangesAsync(); } var id = obj._id; objects? loaded; await using (var db = await contexts.CreateDbContextAsync()) loaded = await db.objects.FirstOrDefaultAsync(o => o._id == id); sw.Stop(); if (loaded == null) return Fail("E166_ef", "EF: Generic with Props=null", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to load saved object."); var result = Ok("E166_ef", "EF: Generic with Props=null", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"ID: {id}, SchemeId: {loaded._id_scheme}", $"value_string: {loaded._value_string}", $"value_long: {loaded._value_long} (no Props row)"]); await using (var db = await contexts.CreateDbContextAsync()) await db.objects.Where(o => o._id == id).ExecuteDeleteAsync(); return result; } } Path: redb/redb.Examples/ExamplesEf/E167_MixedBatch_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E167_MixedBatch_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : two plain header rows and two marked as employees without Props, /// saved and loaded as one batch. /// [ExampleMeta("E167_ef", "EF: Mixed Batch - Generic and Non-Generic", "Core", ExampleTier.Free, 1, "EF", "Base", "Batch")] public class E167_MixedBatch_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var now = DateTime.UtcNow; objects Header(long schemeId, string name, string value, long number) => new() { _id_scheme = schemeId, _date_create = now, _date_modify = now, _name = $"{name}_{now.Ticks}", _value_string = value, _value_long = number }; var batch = new List { Header(EfSchemeIds.None, "Mixed_NonGeneric_1", "NonGeneric", 1), Header(EfSchemeIds.None, "Mixed_NonGeneric_2", "NonGeneric", 2), Header(EfSchemeIds.Employee, "Mixed_Generic_1", "Generic", 3), Header(EfSchemeIds.Employee, "Mixed_Generic_2", "Generic", 4) }; await using (var db = await contexts.CreateDbContextAsync()) { db.objects.AddRange(batch); await db.SaveChangesAsync(); } var ids = batch.Select(o => o._id).ToList(); List loaded; await using (var db = await contexts.CreateDbContextAsync()) loaded = await db.objects.Where(o => ids.Contains(o._id)).ToListAsync(); sw.Stop(); if (loaded.Count != 4) return Fail("E167_ef", "EF: Mixed Batch - Generic and Non-Generic", ExampleTier.Free, sw.ElapsedMilliseconds, $"Expected 4 objects, got {loaded.Count}."); var nonGenCount = loaded.Count(x => x._value_string == "NonGeneric"); var genCount = loaded.Count(x => x._value_string == "Generic"); var result = Ok("E167_ef", "EF: Mixed Batch - Generic and Non-Generic", ExampleTier.Free, sw.ElapsedMilliseconds, loaded.Count, [$"Total: {loaded.Count} objects", $"Non-Generic: {nonGenCount}, Generic: {genCount}", $"IDs: [{string.Join(", ", ids)}]"]); await using (var db = await contexts.CreateDbContextAsync()) await db.objects.Where(o => ids.Contains(o._id)).ExecuteDeleteAsync(); return result; } } Path: redb/redb.Examples/ExamplesEf/E168_ArrayContains_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E168_ArrayContains_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Skills contains "C#", up to 100 whole objects and the count. [ExampleMeta("E168_ef", "EF: Array - Contains", "Query", ExampleTier.Free, 1, "EF", "Array", "Contains")] public class E168_ArrayContains_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.EmployeeProps_Skills.Any(s => s._value == "C#")); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var skillSamples = results.Take(3) .Select(e => $"{e.Props.FirstName}: [{string.Join(", ", e.Props.Skills?.Take(3) ?? [])}]"); return Ok("E168_ef", "EF: Array - Contains", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, ["Filter: Skills.Contains(\"C#\")", $"Found: {totalCount} employees", $"Samples: {string.Join("; ", skillSamples)}"]); } } Path: redb/redb.Examples/ExamplesEf/E169_ArrayContainsOr_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E169_ArrayContainsOr_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Skills contains "C#" or "Python", up to 100 whole objects and the count. [ExampleMeta("E169_ef", "EF: Array - Contains OR", "Query", ExampleTier.Free, 1, "EF", "Array", "Contains")] public class E169_ArrayContainsOr_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.EmployeeProps_Skills.Any(s => s._value == "C#") || e.EmployeeProps_Skills.Any(s => s._value == "Python")); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var csharpCount = results.Count(e => e.Props.Skills?.Contains("C#") == true); var pythonCount = results.Count(e => e.Props.Skills?.Contains("Python") == true); return Ok("E169_ef", "EF: Array - Contains OR", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, ["Filter: Skills.Contains(\"C#\") OR Skills.Contains(\"Python\")", $"Found: {totalCount} employees", $"C# devs: {csharpCount}, Python devs: {pythonCount}"]); } } Path: redb/redb.Examples/ExamplesEf/E170_ArrayContainsAnd_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E170_ArrayContainsAnd_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Skills contains both "C#" and "SQL", up to 100 whole objects and the count. [ExampleMeta("E170_ef", "EF: Array - Contains AND", "Query", ExampleTier.Free, 1, "EF", "Array", "Contains")] public class E170_ArrayContainsAnd_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.EmployeeProps_Skills.Any(s => s._value == "C#") && e.EmployeeProps_Skills.Any(s => s._value == "SQL")); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var skillSamples = results.Take(3) .Select(e => $"{e.Props.FirstName}: [{string.Join(", ", e.Props.Skills ?? [])}]"); return Ok("E170_ef", "EF: Array - Contains AND", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, ["Filter: Skills.Contains(\"C#\") AND Skills.Contains(\"SQL\")", $"Found: {totalCount} full-stack employees", $"Samples: {string.Join("; ", skillSamples)}"]); } } Path: redb/redb.Examples/ExamplesEf/E171_ScalarPlusArray_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E171_ScalarPlusArray_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : Age above 30 and Skills contains "C#", up to 100 whole objects and the count. [ExampleMeta("E171_ef", "EF: Scalar + Array Combined", "Query", ExampleTier.Free, 1, "EF", "Array", "Where")] public class E171_ScalarPlusArray_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.Age > 30 && e.EmployeeProps_Skills.Any(s => s._value == "C#")); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var avgAge = results.Any() ? results.Average(e => e.Props.Age) : 0; var sample = results.FirstOrDefault(); return Ok("E171_ef", "EF: Scalar + Array Combined", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, ["Filter: Age > 30 AND Skills.Contains(\"C#\")", $"Found: {totalCount} senior C# developers", $"Avg age: {avgAge:F1}, Sample: {sample?.Props.FirstName} ({sample?.Props.Age})"]); } } Path: redb/redb.Examples/ExamplesEf/E172_StringLength_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E172_StringLength_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : LastName.Length above 6, up to 100 whole objects and the count. [ExampleMeta("E172_ef", "EF: String.Length Filter", "Query", ExampleTier.Free, 1, "EF", "Where", "String")] public class E172_StringLength_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var filtered = db.EmployeeProps.Where(e => e.LastName!.Length > 6); var results = await filtered.WithGraph().OrderBy(e => e._id).Take(100).ToBusinessListAsync(); var totalCount = await filtered.CountAsync(); sw.Stop(); var names = results.Take(5).Select(e => $"{e.Props.LastName} ({e.Props.LastName.Length} chars)"); return Ok("E172_ef", "EF: String.Length Filter", ExampleTier.Free, sw.ElapsedMilliseconds, totalCount, ["Filter: LastName.Length > 6", $"Found: {totalCount} employees", $"Samples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/ExamplesEf/E173_TreeQueryGroupBy_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E173_TreeQueryGroupBy_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a grouping over the whole subtree of a root. [ExampleMeta("E173_ef", "EF: TreeQuery - GroupBy", "Tree", ExampleTier.Free, 1, "EF", "Tree")] public class E173_TreeQueryGroupBy_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E173_ef", "EF: TreeQuery - GroupBy", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E174_TreeQueryWindow_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E174_TreeQueryWindow_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : window functions over the whole subtree of a root. [ExampleMeta("E174_ef", "EF: TreeQuery - Window Functions", "Tree", ExampleTier.Free, 1, "EF", "Tree")] public class E174_TreeQueryWindow_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E174_ef", "EF: TreeQuery - Window Functions", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E175_TreeQueryGroupByWindow_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E175_TreeQueryGroupByWindow_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : grouping and window functions over the whole subtree of a root. [ExampleMeta("E175_ef", "EF: TreeQuery - GroupBy + Window", "Tree", ExampleTier.Pro, 1, "EF", "Tree")] public class E175_TreeQueryGroupByWindow_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E175_ef", "EF: TreeQuery - GroupBy + Window", ExampleTier.Pro, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E176_TreeDistinctBy_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E176_TreeDistinctBy_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a distinct over the whole subtree of a root. [ExampleMeta("E176_ef", "EF: TreeQuery - DistinctBy", "Tree", ExampleTier.Pro, 1, "EF", "Tree")] public class E176_TreeDistinctBy_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E176_ef", "EF: TreeQuery - DistinctBy", ExampleTier.Pro, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E177_TreeDistinctByRedb_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E177_TreeDistinctByRedb_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a distinct by a header field over the whole subtree of a root. [ExampleMeta("E177_ef", "EF: TreeQuery - DistinctByRedb", "Tree", ExampleTier.Pro, 1, "EF", "Tree")] public class E177_TreeDistinctByRedb_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E177_ef", "EF: TreeQuery - DistinctByRedb", ExampleTier.Pro, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E178_TreeOrderBy_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E178_TreeOrderBy_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a sorted page of the whole subtree of a root. [ExampleMeta("E178_ef", "EF: TreeQuery - OrderBy", "Tree", ExampleTier.Free, 1, "EF", "Tree")] public class E178_TreeOrderBy_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E178_ef", "EF: TreeQuery - OrderBy", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E179_TreeOrderByDescending_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E179_TreeOrderByDescending_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a sorted page of the whole subtree of a root. [ExampleMeta("E179_ef", "EF: TreeQuery - OrderByDescending", "Tree", ExampleTier.Free, 1, "EF", "Tree")] public class E179_TreeOrderByDescending_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E179_ef", "EF: TreeQuery - OrderByDescending", ExampleTier.Free, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E180_TreeDistinctByOrderBy_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E180_TreeDistinctByOrderBy_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a distinct and sorted page of the whole subtree of a root. [ExampleMeta("E180_ef", "EF: TreeQuery - DistinctBy + OrderBy", "Tree", ExampleTier.Pro, 1, "EF", "Tree")] public class E180_TreeDistinctByOrderBy_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E180_ef", "EF: TreeQuery - DistinctBy + OrderBy", ExampleTier.Pro, "EF Core has no recursive query (WITH RECURSIVE) for a tree of any depth")); } Path: redb/redb.Examples/ExamplesEf/E181_DeleteSingle_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E181_DeleteSingle_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : create an employee, load it, delete it, load it again. /// /// The delete removes the header row in objects; the Props row and every nested row go with it /// because the flat schema declares ON DELETE CASCADE, as redb does for its own rows. Without that in the /// schema, an EF application has to configure the cascade itself (OnDelete(DeleteBehavior.Cascade)) /// or load and remove the whole graph. /// /// [ExampleMeta("E181_ef", "EF: Delete - Single Object", "CRUD", ExampleTier.Free, 181, "EF", "Delete")] public class E181_DeleteSingle_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var header = EmployeeEfMapping.ToEntity(new RedbObject { name = $"ToDelete_{DateTime.UtcNow.Ticks}", Props = new Biz.EmployeeProps { FirstName = "Temporary", LastName = "Employee", Age = 25, Salary = 50000m, Department = "Test" } }); db.objects.Add(header); await db.SaveChangesAsync(); var id = header._id; // Verify it exists: loaded as a whole object, as redb's LoadAsync does. var before = await db.EmployeeProps.WithGraph().FirstOrDefaultAsync(e => e._id == id); var existsBefore = before != null && EmployeeEfGraph.ToBusiness(before) != null; db.objects.Remove(header); await db.SaveChangesAsync(); var after = await db.EmployeeProps.WithGraph().FirstOrDefaultAsync(e => e._id == id); var existsAfter = after != null; sw.Stop(); if (!existsBefore || existsAfter) { return Fail("E181_ef", "EF: Delete - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, $"Delete verification failed. Before: {existsBefore}, After: {existsAfter}"); } return Ok("E181_ef", "EF: Delete - Single Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Created object ID: {id}", $"Existed before delete: {existsBefore}", $"Existed after delete: {existsAfter}"]); } } Path: redb/redb.Examples/ExamplesEf/E182_DeleteBatch_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E182_DeleteBatch_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : five employees saved, loaded as whole objects, deleted in one /// statement (the cascade removes their Props rows) and looked up again. /// [ExampleMeta("E182_ef", "EF: Delete - Batch", "Core", ExampleTier.Free, 1, "EF", "Delete")] public class E182_DeleteBatch_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var batchId = DateTime.UtcNow.Ticks; var headers = Enumerable.Range(0, 5).Select(i => EmployeeEfMapping.ToEntity(new RedbObject { name = $"BatchDelete_{batchId}_{i}", Props = new Biz.EmployeeProps { FirstName = $"Temp{i}", LastName = "Employee", Age = 20 + i, Salary = 40000m + i * 1000, Department = "Test" } })).ToList(); await using (var db = await contexts.CreateDbContextAsync()) { db.objects.AddRange(headers); await db.SaveChangesAsync(); } var ids = headers.Select(h => h._id).ToList(); int countBefore; await using (var db = await contexts.CreateDbContextAsync()) countBefore = (await db.EmployeeProps.WithGraph().Where(e => ids.Contains(e._id)).ToBusinessListAsync()).Count; await using (var db = await contexts.CreateDbContextAsync()) await db.objects.Where(o => ids.Contains(o._id)).ExecuteDeleteAsync(); int countAfter; await using (var db = await contexts.CreateDbContextAsync()) countAfter = (await db.EmployeeProps.WithGraph().Where(e => ids.Contains(e._id)).ToBusinessListAsync()).Count; sw.Stop(); return Ok("E182_ef", "EF: Delete - Batch", ExampleTier.Free, sw.ElapsedMilliseconds, ids.Count, [$"Created: {ids.Count} objects", $"Before delete: {countBefore}", $"After delete: {countAfter}"]); } } Path: redb/redb.Examples/ExamplesEf/E183_FirstOrDefaultAsync_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E183_FirstOrDefaultAsync_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : the top earner above 80000 as a whole object, and a miss. [ExampleMeta("E183_ef", "EF: FirstOrDefaultAsync", "Query", ExampleTier.Free, 1, "EF")] public class E183_FirstOrDefaultAsync_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var highEarnerEntity = await db.EmployeeProps.WithGraph() .Where(e => e.Salary > 80000m) .OrderByDescending(e => e.Salary) .FirstOrDefaultAsync(); var highEarner = highEarnerEntity == null ? null : EmployeeEfGraph.ToBusiness(highEarnerEntity); var notFoundEntity = await db.EmployeeProps.WithGraph() .Where(e => e.Salary > 10_000_000m) .OrderBy(e => e._id) // EF's own need with split queries, as in the other twins .FirstOrDefaultAsync(); sw.Stop(); if (highEarner == null) { return Fail("E183_ef", "EF: FirstOrDefaultAsync", ExampleTier.Free, sw.ElapsedMilliseconds, "No employees with salary > 80000 found."); } return Ok("E183_ef", "EF: FirstOrDefaultAsync", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"First high earner: {highEarner.Props.FirstName} {highEarner.Props.LastName}", $"Salary: ${highEarner.Props.Salary:N0}", $"Not found (null): {notFoundEntity == null}"]); } } Path: redb/redb.Examples/ExamplesEf/E184_WhereNullable_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E184_WhereNullable_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : EmployeeCode null and not null, five whole objects and a /// count of each. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E184_ef", "EF: Where - Nullable Field", "Query", ExampleTier.Free, 1, "EF")] public class E184_WhereNullable_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var withoutCode = await db.EmployeeProps.WithGraph().Where(e => e.EmployeeCode == null).OrderBy(e => e._id).Take(5).ToBusinessListAsync(); var nullCount = await db.EmployeeProps.Where(e => e.EmployeeCode == null).CountAsync(); var withCode = await db.EmployeeProps.WithGraph().Where(e => e.EmployeeCode != null).OrderBy(e => e._id).Take(5).ToBusinessListAsync(); var notNullCount = await db.EmployeeProps.Where(e => e.EmployeeCode != null).CountAsync(); sw.Stop(); var sampleCode = withCode.FirstOrDefault()?.Props?.EmployeeCode ?? "N/A"; return Ok("E184_ef", "EF: Where - Nullable Field", ExampleTier.Free, sw.ElapsedMilliseconds, nullCount + notNullCount, [$"EmployeeCode == null: {nullCount}", $"EmployeeCode != null: {notNullCount}", $"Sample code: {sampleCode}"]); } } Path: redb/redb.Examples/ExamplesEf/E185_WhereBool_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E185_WhereBool_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : two counts and five whole objects under combined conditions. /// OrderBy(_id) is EF's own need, the redb query has none: with split queries and Take, every child query must pick the same employees. /// [ExampleMeta("E185_ef", "EF: Where - Combined Conditions", "Query", ExampleTier.Free, 1, "EF")] public class E185_WhereBool_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var expHighEarnersCount = await db.EmployeeProps.Where(e => e.Age > 30 && e.Salary > 70000m).CountAsync(); var expHighEarners = await db.EmployeeProps.WithGraph() .Where(e => e.Age > 30 && e.Salary > 70000m) .OrderBy(e => e._id) .Take(5) .ToBusinessListAsync(); var techDeptCount = await db.EmployeeProps.Where(e => e.Department == "IT" || e.Department == "Engineering").CountAsync(); sw.Stop(); var names = expHighEarners.Take(3).Select(e => $"{e.Props.FirstName} ({e.Props.Age}, ${e.Props.Salary:N0})"); return Ok("E185_ef", "EF: Where - Combined Conditions", ExampleTier.Free, sw.ElapsedMilliseconds, expHighEarnersCount + techDeptCount, [$"Age > 30 AND Salary > 70000: {expHighEarnersCount}", $"IT OR Engineering: {techDeptCount}", $"Samples: {string.Join(", ", names)}"]); } } Path: redb/redb.Examples/ExamplesEf/E186_ObjectReference_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E186_ObjectReference_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a project, an employee whose CurrentProject points at it, /// and the employee loaded whole with the referenced project and its header included. Both are deleted after. /// [ExampleMeta("E186_ef", "EF: Object Reference - Load", "Core", ExampleTier.Free, 1, "EF", "Reference")] public class E186_ObjectReference_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var now = DateTime.UtcNow; var project = new objects { _id_scheme = EfSchemeIds.ProjectMetrics, _date_create = now, _date_modify = now, _name = $"RefProject_{now.Ticks}", ProjectMetricsProps = new ProjectMetricsProps { ProjectId = 1001, TasksCompleted = 50, TasksTotal = 100, Budget = 500000 } }; await using (var db = await contexts.CreateDbContextAsync()) { db.objects.Add(project); await db.SaveChangesAsync(); } var employee = EmployeeEfMapping.ToEntity(new RedbObject { name = $"RefEmployee_{now.Ticks}", Props = new Biz.EmployeeProps { FirstName = "John", LastName = "ProjectManager", Age = 35, Salary = 90000m, Department = "Engineering" } }); employee.EmployeeProps!.CurrentProject = project._id; await using (var db = await contexts.CreateDbContextAsync()) { db.objects.Add(employee); await db.SaveChangesAsync(); } EmployeeProps? loaded; await using (var db = await contexts.CreateDbContextAsync()) { loaded = await db.EmployeeProps.WithGraph() .Include(e => e.CurrentProjectNavigation!).ThenInclude(p => p.objects) .FirstOrDefaultAsync(e => e._id == employee._id); } sw.Stop(); await using (var db = await contexts.CreateDbContextAsync()) { await db.objects.Where(o => o._id == employee._id).ExecuteDeleteAsync(); await db.objects.Where(o => o._id == project._id).ExecuteDeleteAsync(); } if (loaded?.CurrentProjectNavigation == null) return Fail("E186_ef", "EF: Object Reference - Load", ExampleTier.Free, sw.ElapsedMilliseconds, "CurrentProject reference not loaded."); var business = EmployeeEfGraph.ToBusiness(loaded); return Ok("E186_ef", "EF: Object Reference - Load", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Employee: {business.Props.FirstName} {business.Props.LastName}", $"Project: {loaded.CurrentProjectNavigation.objects._name}", $"Project Budget: ${loaded.CurrentProjectNavigation.Budget ?? 0:N0}"]); } } Path: redb/redb.Examples/ExamplesEf/E187_UpdateExisting_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E187_UpdateExisting_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : an employee saved, loaded whole with tracking, three fields /// changed and saved, loaded again to verify, then deleted. /// [ExampleMeta("E187_ef", "EF: Update - Existing Object", "CRUD", ExampleTier.Free, 1, "EF", "Update")] public class E187_UpdateExisting_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var original = EmployeeEfMapping.ToEntity(new RedbObject { name = $"ToUpdate_{DateTime.UtcNow.Ticks}", Props = new Biz.EmployeeProps { FirstName = "Original", LastName = "Name", Age = 30, Salary = 60000m, Department = "Sales" } }); await using (var db = await contexts.CreateDbContextAsync()) { db.objects.Add(original); await db.SaveChangesAsync(); } var id = original._id; var originalSalary = original.EmployeeProps!.Salary; await using (var db = await contexts.CreateDbContextAsync()) { var loaded = await db.EmployeeProps.WithGraph().FirstOrDefaultAsync(e => e._id == id); if (loaded == null) { sw.Stop(); return Fail("E187_ef", "EF: Update - Existing Object", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to load object for update."); } loaded.FirstName = "Updated"; loaded.Salary = 75000m; loaded.Department = "Engineering"; loaded.objects._date_modify = DateTime.UtcNow; await db.SaveChangesAsync(); } RedbObject? verified; await using (var db = await contexts.CreateDbContextAsync()) verified = (await db.EmployeeProps.WithGraph().Where(e => e._id == id).ToBusinessListAsync()).FirstOrDefault(); sw.Stop(); await using (var db = await contexts.CreateDbContextAsync()) await db.objects.Where(o => o._id == id).ExecuteDeleteAsync(); if (verified == null) return Fail("E187_ef", "EF: Update - Existing Object", ExampleTier.Free, sw.ElapsedMilliseconds, "Failed to verify updated object."); return Ok("E187_ef", "EF: Update - Existing Object", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Original: FirstName='Original', Salary=${originalSalary:N0}", $"Updated: FirstName='{verified.Props.FirstName}', Salary=${verified.Props.Salary:N0}", $"Department changed: Sales -> {verified.Props.Department}"]); } } Path: redb/redb.Examples/ExamplesEf/E188_SoftDeleteReference_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E188_SoftDeleteReference_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a reference to a soft-deleted object. EF Core has no soft delete. [ExampleMeta("E188_ef", "EF: Soft-Delete - Nested Reference Not Materialized", "Core", ExampleTier.Free, 1, "EF", "SoftDelete")] public class E188_SoftDeleteReference_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E188_ef", "EF: Soft-Delete - Nested Reference Not Materialized", ExampleTier.Free, "EF Core has no soft delete (trash) for objects")); } Path: redb/redb.Examples/ExamplesEf/E190_SumAsyncFiltered_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E190_SumAsyncFiltered_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : SUM(Salary) of Engineering and of everyone, two queries. [ExampleMeta("E190_ef", "EF: SumAsync - With Filter", "Analytics", ExampleTier.Free, 1, "EF", "Sum")] public class E190_SumAsyncFiltered_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var engineeringSalary = await db.EmployeeProps.Where(x => x.Department == "Engineering").SumAsync(x => x.Salary) ?? 0m; var totalSalary = await db.EmployeeProps.SumAsync(x => x.Salary) ?? 0m; var berlinFloors = await db.EmployeeProps .Where(x => x.EmployeeProps_HomeAddress!.City == "Berlin") .SumAsync(x => x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor) ?? 0; sw.Stop(); return Ok("E190_ef", "EF: SumAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Engineering SUM: {engineeringSalary:N0}", $"Total SUM: {totalSalary:N0}", $"Ratio: {(totalSalary > 0 ? engineeringSalary / totalSalary * 100 : 0):F1}%", $"Berlin SUM(HomeAddress.Building.Floor): {berlinFloors:N0}"]); } } Path: redb/redb.Examples/ExamplesEf/E191_WindowFiltered_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E191_WindowFiltered_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : ROW_NUMBER over a partition after a filter, which EF Core cannot express. [ExampleMeta("E191_ef", "EF: Window - With Filter", "Analytics", ExampleTier.Free, 1, "EF", "Window")] public class E191_WindowFiltered_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E191_ef", "EF: Window - With Filter", ExampleTier.Free, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E192_AggregateFiltered_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E192_AggregateFiltered_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : five aggregates over the developers in one query. [ExampleMeta("E192_ef", "EF: AggregateAsync - With Filter", "Analytics", ExampleTier.Free, 1, "EF", "Aggregate")] public class E192_AggregateFiltered_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var stats = await db.EmployeeProps .Where(x => x.Position == "Developer" && x.EmployeeProps_HomeAddress!.City != "Tokyo") .Select(x => new { x.Salary, Floor = x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor }) .GroupBy(_ => 1) .Select(g => new { TotalSalary = g.Sum(x => x.Salary), AvgSalary = g.Average(x => x.Salary), MinSalary = g.Min(x => x.Salary), MaxSalary = g.Max(x => x.Salary), MinFloor = g.Min(x => x.Floor), MaxFloor = g.Max(x => x.Floor), AvgFloor = g.Average(x => x.Floor), Count = g.Count() }) .FirstOrDefaultAsync(); sw.Stop(); return Ok("E192_ef", "EF: AggregateAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [ "Filter: Position = 'Developer' AND HomeAddress.City != 'Tokyo'", $"Count: {stats?.Count ?? 0}", $"Salary: {stats?.MinSalary:N0} - {stats?.MaxSalary:N0} (Avg: {stats?.AvgSalary:N0})", $"Home floor: {stats?.MinFloor} - {stats?.MaxFloor} (Avg: {stats?.AvgFloor:F2})" ]); } } Path: redb/redb.Examples/ExamplesEf/E193_AverageAsyncFiltered_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E193_AverageAsyncFiltered_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : AVG(Salary) of ages 30 to 40 and of everyone, two queries. [ExampleMeta("E193_ef", "EF: AverageAsync - With Filter", "Analytics", ExampleTier.Free, 1, "EF", "Average")] public class E193_AverageAsyncFiltered_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var avgSalaryMiddle = await db.EmployeeProps.Where(x => x.Age >= 30 && x.Age <= 40).AverageAsync(x => x.Salary); var avgSalaryAll = await db.EmployeeProps.AverageAsync(x => x.Salary); var avgFloorLondon = await db.EmployeeProps .Where(x => x.EmployeeProps_HomeAddress!.City == "London") .AverageAsync(x => x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor); sw.Stop(); return Ok("E193_ef", "EF: AverageAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [$"Age 30-40 AVG: {avgSalaryMiddle:N0}", $"All AVG: {avgSalaryAll:N0}", $"London AVG(HomeAddress.Building.Floor): {avgFloorLondon:F2}"]); } } Path: redb/redb.Examples/ExamplesEf/E194_MinMaxAsyncFiltered_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E194_MinMaxAsyncFiltered_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : MIN and MAX of Salary in Sales and overall, four queries as in redb. [ExampleMeta("E194_ef", "EF: MinMaxAsync - With Filter", "Analytics", ExampleTier.Free, 1, "EF", "Min", "Max")] public class E194_MinMaxAsyncFiltered_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var sales = db.EmployeeProps.Where(x => x.Department == "Sales"); var minSalary = await sales.MinAsync(x => x.Salary); var maxSalary = await sales.MaxAsync(x => x.Salary); var minAll = await db.EmployeeProps.MinAsync(x => x.Salary); var maxAll = await db.EmployeeProps.MaxAsync(x => x.Salary); var berlin = db.EmployeeProps.Where(x => x.EmployeeProps_HomeAddress!.City == "Berlin"); var minFloor = await berlin.MinAsync(x => x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor); var maxFloor = await berlin.MaxAsync(x => x.EmployeeProps_HomeAddress!.EmployeeProps_HomeAddress_Building!.Floor); sw.Stop(); return Ok("E194_ef", "EF: MinMaxAsync - With Filter", ExampleTier.Free, sw.ElapsedMilliseconds, 1, [ $"Sales: {minSalary:N0} - {maxSalary:N0}", $"All: {minAll:N0} - {maxAll:N0}", $"Berlin HomeAddress.Building.Floor: {minFloor} - {maxFloor}" ]); } } Path: redb/redb.Examples/ExamplesEf/E195_GroupByWindowFiltered_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E195_GroupByWindowFiltered_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : RANK over grouped totals, which EF Core cannot express. [ExampleMeta("E195_ef", "EF: GroupBy + Window - With Filter", "Analytics", ExampleTier.Pro, 1, "EF", "Window", "GroupBy")] public class E195_GroupByWindowFiltered_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E195_ef", "EF: GroupBy + Window - With Filter", ExampleTier.Pro, "EF Core does not translate window functions (dotnet/efcore#12747)")); } Path: redb/redb.Examples/ExamplesEf/E200_SmokeSqlDump_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E200_SmokeSqlDump_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a dump of redb's own SQL for diffing two redb builders. [ExampleMeta("E200_ef", "EF: SQL dump for smoke cases (Pro vs PVT)", "Query", ExampleTier.Pro, 1, "EF", "Debug")] public class E200_SmokeSqlDump_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E200_ef", "EF: SQL dump for smoke cases (Pro vs PVT)", ExampleTier.Pro, "Diagnostic of redb's own SQL builders, no task to repeat in EF Core")); } Path: redb/redb.Examples/ExamplesEf/E201_NullCheckBaseIdAmbiguity_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E201_NullCheckBaseIdAmbiguity_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : a regression probe of redb's own SQL builder. [ExampleMeta("E201_ef", "EF: NullCheck + base Id: ambiguous _id in PVT CTE", "Query", ExampleTier.Pro, 1, "EF", "Debug")] public class E201_NullCheckBaseIdAmbiguity_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E201_ef", "EF: NullCheck + base Id: ambiguous _id in PVT CTE", ExampleTier.Pro, "Diagnostic of redb's own SQL builders, no task to repeat in EF Core")); } Path: redb/redb.Examples/ExamplesEf/E202_PvtPrefilter_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E202_PvtPrefilter_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : redb's SQL with and without its own prefilter step. [ExampleMeta("E202_ef", "EF: PVT prefilter: SQL with and without the cutting step", "Query", ExampleTier.Pro, 1, "EF", "Debug")] public class E202_PvtPrefilter_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E202_ef", "EF: PVT prefilter: SQL with and without the cutting step", ExampleTier.Pro, "Diagnostic of redb's own SQL builders, no task to repeat in EF Core")); } Path: redb/redb.Examples/ExamplesEf/E203_SeedVolume_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E203_SeedVolume_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Ef.Entities; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : seeds the same employees, arranged as the same reporting /// tree, into the flat database, with EF Core's own means only. /// /// Same generator (E000_BulkInsert.CreateEmployees, deterministic), same batch size, same tree /// (every manager has direct reports), same environment variables. What is /// EF's own: the business class is mapped to the entity graph by hand (), /// each batch is one unit of work in a new context with change tracking on, written by /// SaveChangesAsync; keys come from the database sequence. No bulk copy, no raw SQL in the /// measured part. /// /// /// dotnet run --project redb.Examples -- E203_ef /// REDB_SEED_COUNT=20000 dotnet run --project redb.Examples -- E203_ef /// /// /// Like E203, it seeds only when named on the command line, appends and never clears. /// /// [ExampleMeta("E203_ef", "EF: seed volume, employees as a reporting tree", "Setup", ExampleTier.Pro, 200, "Setup", "BulkInsert", "Tree", "Benchmark", "EF")] public class E203_SeedVolume_ef : EfExampleBase { /// How many people report to one manager. private const int DirectReports = 10; public override async Task RunEfAsync(IDbContextFactory contexts) { const string id = "E203_ef"; const string title = "EF: seed volume, employees as a reporting tree"; var isExplicitRun = ExplicitlyRequestedIds?.Contains("E203_EF") == true; var total = ReadInt("REDB_SEED_COUNT", isExplicitRun ? 100_000 : 0); var batchSize = ReadInt("REDB_SEED_BATCH", 1_000); if (total == 0) { return Ok(id, title, ExampleTier.Pro, 0, [ "Skipped: the whole-suite sweep never seeds.", "To seed: dotnet run --project redb.Examples -- E203_ef (default 100000)", "REDB_SEED_COUNT overrides the size, REDB_SEED_BATCH the batch (default 1000)." ]) with { Skipped = true }; } if (total < 0 || batchSize <= 0) return Fail(id, title, ExampleTier.Pro, 0, "REDB_SEED_COUNT must not be negative and REDB_SEED_BATCH must be positive"); // Continue numbering after whatever is already there, as E203 does. int existing; await using (var db = await contexts.CreateDbContextAsync()) existing = await db.EmployeeProps.CountAsync(); Console.WriteLine(); Console.WriteLine($"Seeding {total:N0} employees through EF Core in batches of {batchSize:N0}, {DirectReports} direct reports per manager"); Console.WriteLine($"Already in the flat database: {existing:N0}. New objects start at index {existing:N0}."); Console.WriteLine(); var sw = Stopwatch.StartNew(); // As E203 sets redb's plain indexes aside before its load, the developer's indexes go before this // one; they are created again after it, inside the measured time. await DropDeveloperIndexesAsync(contexts); // Header key of every seeded position, known once its batch is saved. A manager always comes // earlier than the reports, so it is already saved or sits in the same batch. var keys = new long[total]; var batchTimer = new Stopwatch(); var seeded = 0; var batches = 0; while (seeded < total) { var take = Math.Min(batchSize, total - seeded); batchTimer.Restart(); var employees = E000_BulkInsert.CreateEmployees(take, existing + seeded); // One unit of work per batch, in a context of its own: a context that tracked every batch // would slow down with each SaveChanges. await using var db = await contexts.CreateDbContextAsync(); var headers = new objects[take]; for (var i = 0; i < take; i++) { var position = seeded + i; var header = EmployeeEfMapping.ToEntity(employees[i]); if (position > 0) { var managerPosition = (position - 1) / DirectReports; if (managerPosition >= seeded) header._id_parentNavigation = headers[managerPosition - seeded]; // same batch: EF orders the inserts else header._id_parent = keys[managerPosition]; // an earlier batch: key is known } headers[i] = header; } db.objects.AddRange(headers); await db.SaveChangesAsync(); for (var i = 0; i < take; i++) keys[seeded + i] = headers[i]._id; batchTimer.Stop(); seeded += take; batches++; var pct = seeded * 100.0 / total; var overallRate = seeded * 1000.0 / Math.Max(sw.ElapsedMilliseconds, 1); var remaining = overallRate > 0 ? TimeSpan.FromSeconds((total - seeded) / overallRate) : TimeSpan.Zero; Console.WriteLine( $"[{seeded,8:N0}/{total:N0}] {pct,5:F1}% " + $"batch {batchTimer.ElapsedMilliseconds,6:N0} ms " + $"avg {overallRate,7:F0} obj/s " + $"elapsed {sw.Elapsed:hh\\:mm\\:ss} " + $"ETA {remaining:hh\\:mm\\:ss}"); } // The developer's indexes for the EF twins' queries (Ef/developer_indexes.sql), built after the seed and // inside the measured time, as E203 rebuilds redb's indexes after its seed. await CreateDeveloperIndexesAsync(contexts); sw.Stop(); int finalCount; await using (var db = await contexts.CreateDbContextAsync()) { finalCount = await db.EmployeeProps.CountAsync(); // Same step as E203, outside the measured time. EF has no API to refresh planner statistics, // so this one maintenance statement goes as SQL; it is not a query and not part of the seed. Console.WriteLine(); Console.WriteLine("Refreshing planner statistics (ANALYZE)..."); await db.Database.ExecuteSqlRawAsync("ANALYZE"); } var rate = seeded * 1000.0 / Math.Max(sw.ElapsedMilliseconds, 1); return Ok(id, title, ExampleTier.Pro, sw.ElapsedMilliseconds, seeded, [ $"Seeded {seeded:N0} in {batches:N0} batches of {batchSize:N0}", $"Rate: {rate:F0} obj/sec | flat database now holds {finalCount:N0} employees", $"Reporting tree head: objects._id {keys[0]}" ]); } /// The statements of Ef/developer_indexes.sql, one per line; lines starting with -- are skipped. private static List DeveloperIndexStatements() { var path = Path.Combine(AppContext.BaseDirectory, "Ef", "developer_indexes.sql"); return File.ReadAllLines(path) .Select(line => line.Trim()) .Where(line => line.Length > 0 && !line.StartsWith("--", StringComparison.Ordinal)) .ToList(); } /// /// Drops the indexes Ef/developer_indexes.sql creates, when they are there: the name is the quoted /// identifier after CREATE INDEX. /// private static async Task DropDeveloperIndexesAsync(IDbContextFactory contexts) { var names = DeveloperIndexStatements() .Where(s => s.StartsWith("CREATE INDEX \"", StringComparison.OrdinalIgnoreCase)) .Select(s => s[(s.IndexOf('"') + 1)..]) .Select(rest => rest[..rest.IndexOf('"')]) .ToList(); Console.WriteLine($"Dropping {names.Count} developer indexes before the load (Ef/developer_indexes.sql)..."); await using var db = await contexts.CreateDbContextAsync(); foreach (var name in names) { var drop = "DROP INDEX IF EXISTS \"" + name.Replace("\"", "\"\"") + "\""; await db.Database.ExecuteSqlRawAsync(drop); } } /// /// Runs Ef/developer_indexes.sql. EF has no API for indexes outside migrations, so the script goes as SQL: /// schema maintenance, not a query. /// private static async Task CreateDeveloperIndexesAsync(IDbContextFactory contexts) { var statements = DeveloperIndexStatements(); Console.WriteLine(); Console.WriteLine($"Creating {statements.Count} developer indexes (Ef/developer_indexes.sql)..."); var timer = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); foreach (var statement in statements) await db.Database.ExecuteSqlRawAsync(statement); timer.Stop(); Console.WriteLine($"Developer indexes created in {timer.ElapsedMilliseconds:N0} ms"); } private static int ReadInt(string name, int fallback) { var raw = Environment.GetEnvironmentVariable(name); return int.TryParse(raw, out var parsed) ? parsed : fallback; } } Path: redb/redb.Examples/ExamplesEf/E204_TreePrefilter_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E204_TreePrefilter_ef.cs ---- using Microsoft.EntityFrameworkCore; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// EF Core twin of : filtered counts inside a subtree of any depth. [ExampleMeta("E204_ef", "EF: PVT prefilter in tree queries", "Trees", ExampleTier.Pro, 1, "EF", "Tree")] public class E204_TreePrefilter_ef : EfExampleBase { public override Task RunEfAsync(IDbContextFactory contexts) => Task.FromResult(NotSupported("E204_ef", "EF: PVT prefilter in tree queries", ExampleTier.Pro, "EF Core has no recursive query (WITH RECURSIVE) for a subtree at any depth")); } Path: redb/redb.Examples/ExamplesEf/E205_WhereRedbSystemFields_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E205_WhereRedbSystemFields_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : saves three employees with a service key and a /// string lookup key in the objects header, finds them by those header fields as whole objects, and /// deletes them again. /// [ExampleMeta("E205_ef", "EF: WhereRedb - System Fields and Composition", "Query", ExampleTier.Free, 1, "EF", "Where", "Base")] public class E205_WhereRedbSystemFields_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var headers = new List(); for (var i = 0; i < 3; i++) { var header = EmployeeEfMapping.ToEntity(new RedbObject { name = $"e205-employee-{i}", Props = new Biz.EmployeeProps { FirstName = $"E205-{i}", LastName = "Sample", Department = i == 2 ? "Sales" : "IT", Salary = 50000m + i * 10000m, }, }); header._key = 7000 + i; header._value_string = i == 0 ? "e205:head-of-desk" : null; headers.Add(header); } db.objects.AddRange(headers); await db.SaveChangesAsync(); var seeded = headers.Select(h => h._id).ToList(); var head = (await db.EmployeeProps.WithGraph() .Where(e => e.objects._value_string == "e205:head-of-desk") .OrderBy(e => e._id) .Take(1) .ToBusinessListAsync()).FirstOrDefault(); var byIds = await db.EmployeeProps.WithGraph() .Where(e => seeded.Contains(e._id)) .ToBusinessListAsync(); var itByKey = await db.EmployeeProps.WithGraph() .Where(e => e.objects._key >= 7000 && e.objects._key <= 7002) .Where(e => e.Department == "IT") .ToBusinessListAsync(); sw.Stop(); // Cleanup outside the measurement, as in redb: the cascade removes the Props rows with the headers. await db.objects.Where(o => seeded.Contains(o._id)).ExecuteDeleteAsync(); return Ok("E205_ef", "EF: WhereRedb - System Fields and Composition", ExampleTier.Free, sw.ElapsedMilliseconds, byIds.Count + itByKey.Count + (head != null ? 1 : 0), [ $"ValueString lookup: {(head != null ? head.name : "")}", $"Contains(Id): {byIds.Count} of {seeded.Count}", $"Key range and Department == IT: {itByKey.Count}", ]); } } Path: redb/redb.Examples/ExamplesEf/E206_WhereRedbNarrowsFirst_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E206_WhereRedbNarrowsFirst_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : a lead with 20 team members under it, then the same /// Props filter and page over the whole set and under the lead (objects._id_parent), as whole objects. /// The team is deleted at the end. /// [ExampleMeta("E206_ef", "EF: WhereRedb - Narrow by Parent First", "Query", ExampleTier.Free, 1, "EF", "Where", "Parent")] public class E206_WhereRedbNarrowsFirst_ef : EfExampleBase { public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); await using var db = await contexts.CreateDbContextAsync(); var lead = EmployeeEfMapping.ToEntity(new RedbObject { name = "e206-team-lead", Props = new Biz.EmployeeProps { FirstName = "E206", LastName = "Lead", Department = "Sales", Salary = 150000m, Age = 45 }, }); var team = Enumerable.Range(0, 20).Select(i => { var member = EmployeeEfMapping.ToEntity(new RedbObject { name = $"e206-member-{i}", Props = new Biz.EmployeeProps { FirstName = $"E206-{i}", LastName = "Member", Department = "Sales", Age = 25 + i, Salary = 60000m + i * 2500m, }, }); member._id_parentNavigation = lead; return member; }).ToList(); db.objects.Add(lead); db.objects.AddRange(team); await db.SaveChangesAsync(); var leadId = lead._id; var whole = Stopwatch.StartNew(); var anywhere = await db.EmployeeProps.WithGraph() .Where(e => e.Salary > 70000m && e.Age >= 30) .OrderByDescending(e => e.Salary).ThenBy(e => e._id) .Take(10) .ToBusinessListAsync(); var wholeMs = whole.ElapsedMilliseconds; var narrow = Stopwatch.StartNew(); var teamPage = await db.EmployeeProps.WithGraph() .Where(e => e.objects._id_parent == leadId) .Where(e => e.Salary > 70000m && e.Age >= 30) .OrderByDescending(e => e.Salary).ThenBy(e => e._id) .Take(10) .ToBusinessListAsync(); var narrowMs = narrow.ElapsedMilliseconds; sw.Stop(); // Cleanup: the members go with the lead through the cascade on _id_parent. await db.objects.Where(o => o._id == leadId).ExecuteDeleteAsync(); return Ok("E206_ef", "EF: WhereRedb - Narrow by Parent First", ExampleTier.Free, sw.ElapsedMilliseconds, teamPage.Count, [ $"Whole set, Salary > 70000 and Age >= 30, top 10 by Salary: {wholeMs} ms ({anywhere.Count} rows)", $"Same, objects._id_parent == lead: {narrowMs} ms ({teamPage.Count} of {team.Count} team members)", ]); } } Path: redb/redb.Examples/ExamplesEf/E997_DateTimeJulianVerify_ef.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/E997_DateTimeJulianVerify_ef.cs ---- using System.Diagnostics; using Microsoft.EntityFrameworkCore; using redb.Core.Models.Entities; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; using Biz = redb.Examples.Models; namespace redb.Examples.ExamplesEf; /// /// EF Core twin of : three employees with far-apart hire dates, three /// date ranges that must each return exactly one of them as a whole object, and the round trip of a date with a /// time of day. Leftovers of an earlier run are removed first, inside the measurement as in redb. /// [ExampleMeta("E997_ef", "EF: DateTime REAL Julian Verify", "Query", ExampleTier.Free, 1, "EF", "DateTime")] public class E997_DateTimeJulianVerify_ef : EfExampleBase { private const string Dept = "JULIAN-VERIFY"; public override async Task RunEfAsync(IDbContextFactory contexts) { var sw = Stopwatch.StartNew(); var lines = new List(); await using (var db = await contexts.CreateDbContextAsync()) await db.objects.Where(o => o.EmployeeProps!.Department == Dept).ExecuteDeleteAsync(); var dPast = new DateTime(2018, 03, 15, 00, 00, 00, DateTimeKind.Utc); var dMiddle = new DateTime(2024, 06, 15, 13, 45, 30, DateTimeKind.Utc); var dFuture = new DateTime(2030, 09, 20, 00, 00, 00, DateTimeKind.Utc); await using (var db = await contexts.CreateDbContextAsync()) { foreach (var (dt, code) in new[] { (dPast, "PAST"), (dMiddle, "MID"), (dFuture, "FUT") }) { db.objects.Add(EmployeeEfMapping.ToEntity(new RedbObject { name = $"JulianVerify-{code}", Props = new Biz.EmployeeProps { FirstName = code, LastName = "Verify", Age = 30, Position = "QA", Department = Dept, Salary = 1m, HireDate = dt, EmployeeCode = $"JV-{code}" } })); } // One save for the three, as redb saves them as one batch. await db.SaveChangesAsync(); } List> midRange, futureOnly, pastOnly; await using (var db = await contexts.CreateDbContextAsync()) { var from2023 = new DateTime(2023, 1, 1, 0, 0, 0, DateTimeKind.Utc); var to2026 = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); var from2029 = new DateTime(2029, 1, 1, 0, 0, 0, DateTimeKind.Utc); var to2020 = new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc); midRange = await db.EmployeeProps.WithGraph() .Where(e => e.Department == Dept && e.HireDate >= from2023 && e.HireDate < to2026) .ToBusinessListAsync(); futureOnly = await db.EmployeeProps.WithGraph() .Where(e => e.Department == Dept && e.HireDate >= from2029) .ToBusinessListAsync(); pastOnly = await db.EmployeeProps.WithGraph() .Where(e => e.Department == Dept && e.HireDate < to2020) .ToBusinessListAsync(); } var failures = new List(); void Expect(string label, List> got, string wantCode) { if (got.Count == 1 && got[0].Props.EmployeeCode == $"JV-{wantCode}") lines.Add($"OK {label}: 1 row = {wantCode}"); else failures.Add($"{label}: expected [1x{wantCode}], got [{string.Join(",", got.Select(g => g.Props.EmployeeCode))}]"); } Expect("[2023,2026)", midRange, "MID"); Expect(">=2029", futureOnly, "FUT"); Expect("<2020", pastOnly, "PAST"); if (midRange.Count == 1) { var rt = midRange[0].Props.HireDate.ToUniversalTime(); var drift = Math.Abs((rt - dMiddle).TotalMilliseconds); if (drift <= 2) lines.Add($"OK round-trip: {rt:yyyy-MM-ddTHH:mm:ss.fff}Z (drift {drift:0.###}ms)"); else failures.Add($"round-trip drift {drift:0.###}ms: got {rt:O}, want {dMiddle:O}"); } sw.Stop(); if (failures.Count > 0) return Fail("E997_ef", "EF: DateTime REAL Julian Verify", ExampleTier.Free, sw.ElapsedMilliseconds, string.Join(" | ", failures)); return Ok("E997_ef", "EF: DateTime REAL Julian Verify", ExampleTier.Free, sw.ElapsedMilliseconds, midRange.Count + futureOnly.Count + pastOnly.Count, lines.ToArray()); } } Path: redb/redb.Examples/ExamplesEf/EfExampleBase.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/ExamplesEf/EfExampleBase.cs ---- using Microsoft.EntityFrameworkCore; using redb.Core; using redb.Examples.Ef; using redb.Examples.Examples; using redb.Examples.Output; namespace redb.Examples.ExamplesEf; /// /// Base class of the EF Core twins of the examples. A twin carries /// the id of its redb example with the suffix _ef, works on the flat database through EF Core only, /// and returns the same result shape, so the runner prints both side by side. /// public abstract class EfExampleBase : ExampleBase { /// /// Factory of contexts over the flat database, set by Program before any EF example runs. A twin /// creates a new context for each unit of work, as EF recommends; the model is built once per process. /// public static IDbContextFactory? Contexts { get; set; } /// public sealed override Task RunAsync(IRedbService redb) => RunEfAsync(Contexts ?? throw new InvalidOperationException( "The EF context factory is not set: EF examples run only from Program.")); /// Runs the example through EF Core. public abstract Task RunEfAsync(IDbContextFactory contexts); /// /// Result of a twin whose task EF Core cannot do out of the box. No raw SQL stands in for the missing /// feature: the comparison table says so instead of showing a time. /// protected static ExampleResult NotSupported(string id, string title, ExampleTier tier, string reason) => new() { Id = id, Title = title, Tier = tier, Success = true, NotSupported = true, ElapsedMs = 0, Output = [reason] }; } Path: redb/redb.Examples/Models/DeviceModels.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Models/DeviceModels.cs ---- using redb.Core.Attributes; namespace redb.Examples.Models; /// /// Device with every V4 key shape beyond the plain scalar one (E004): /// - a key on a scalar INSIDE a nested class (); /// - a key on a whole SUBTREE - the content of a nested class or a collection is the key; /// - ELEMENT keys on collections, scoped to one collection or to the whole scheme; /// - a free-form [RedbTags] marker on the scheme and on a structure. /// [RedbTags("examples,e004")] public class DeviceProps { public string? Title { get; set; } /// Nested class whose Serial is a key: unique per scheme, like a root key. public DeviceIdentity? Identity { get; set; } /// Subtree key: two devices cannot carry the same configuration content. [RedbUnique] public DeviceConfig? Config { get; set; } /// Subtree key on a collection: the ordered list of ports is the key. [RedbUnique] public List? Ports { get; set; } /// Element keys, Collection scope: no duplicate label inside ONE device. [RedbUnique(Scope = UniqueScope.Collection)] public List? Labels { get; set; } /// Element keys, Scheme scope: a MAC address belongs to one device in the whole scheme. [RedbUnique(Scope = UniqueScope.Scheme)] [RedbTags("network")] public List? MacAddresses { get; set; } } public class DeviceIdentity { [RedbUnique] public string? Serial { get; set; } public string? Vendor { get; set; } } public class DeviceConfig { public string? Region { get; set; } public long? Tier { get; set; } } Path: redb/redb.Examples/Models/ExampleModels.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Models/ExampleModels.cs ---- using redb.Core.Models.Entities; using redb.Core.Attributes; namespace redb.Examples.Models; /// /// Tag with priority for categorization. /// public class Tag { public string Name { get; set; } = string.Empty; public int Priority { get; set; } public string? Description { get; set; } } /// /// Project metrics for analytics. /// [RedbScheme("ProjectMetrics")] public class ProjectMetricsProps { public long ProjectId { get; set; } public long? TasksCompleted { get; set; } public long? TasksTotal { get; set; } public long? BugsFixed { get; set; } public double? Budget { get; set; } public long? TeamSize { get; set; } public Tag[]? Tags { get; set; } public string[]? Technologies { get; set; } } /// /// Address with city, street and building details. /// public class Address { public string City { get; set; } = string.Empty; public string Street { get; set; } = string.Empty; public BuildingInfo? Building { get; set; } } /// /// Building information with floor and amenities. /// public class BuildingInfo { public int Floor { get; set; } public string Name { get; set; } = string.Empty; public string[]? Amenities { get; set; } public int[]? AccessCodes { get; set; } public string[]? ParkingSpots { get; set; } public int[]? ElevatorFloors { get; set; } } /// /// Contact detail key-value pair. /// public class ContactDetail { public string Label { get; set; } = string.Empty; public string Value { get; set; } = string.Empty; } /// /// Contact information (email, phone, etc). /// public class Contact { public string Type { get; set; } = string.Empty; public string Value { get; set; } = string.Empty; public bool IsVerified { get; set; } public int[]? NotificationHours { get; set; } public ContactDetail[]? Metadata { get; set; } } /// /// Department info with tags, metrics and nested budget data. /// public class Department { public string Name { get; set; } = string.Empty; public int HeadCount { get; set; } public string[] Projects { get; set; } = []; public Tag[] Leaders { get; set; } = []; public Dictionary? BudgetByYear { get; set; } } /// /// Employee props - main model for examples. /// Demonstrates all supported types: /// - Simple types (int, string, DateTime, long, decimal) /// - Arrays (string[], int[]) /// - Business classes (Address with nested BuildingInfo) /// - Array of business classes (Contact[]) /// - RedbObject references (CurrentProject, PastProjects[]) /// - Dictionary types (various key and value types) /// [RedbScheme("Employee")] public class EmployeeProps { // Basic info public string FirstName { get; set; } = string.Empty; public string LastName { get; set; } = string.Empty; public int Age { get; set; } public DateTime HireDate { get; set; } public string Position { get; set; } = string.Empty; public decimal Salary { get; set; } public string Department { get; set; } = string.Empty; public string? EmployeeCode { get; set; } // Skills and certifications (arrays) public string[]? Skills { get; set; } public int[]? SkillLevels { get; set; } public string[]? Certifications { get; set; } public int[]? CertificationYears { get; set; } // Addresses (business classes) public Address? HomeAddress { get; set; } public Address? WorkAddress { get; set; } public Address? EmergencyAddress { get; set; } // Contacts (array of business classes) public Contact[]? Contacts { get; set; } // Project references (RedbObject) public RedbObject? CurrentProject { get; set; } public RedbObject[]? PastProjects { get; set; } // Phone directory: extension -> phone number public Dictionary? PhoneDirectory { get; set; } // Office locations by city public Dictionary? OfficeLocations { get; set; } // Bonus history by year public Dictionary? BonusByYear { get; set; } // Department details with complex nested data (Pro) public Dictionary? DepartmentHistory { get; set; } // Composite key: (year, quarter) -> performance score (Pro) public Dictionary<(int Year, string Quarter), string>? PerformanceReviews { get; set; } // Project metrics by code (Pro) public Dictionary>? ProjectMetrics { get; set; } } /// /// Department props for tree examples (corporate hierarchy). /// Used with TreeRedbObject for organizational structure. /// Similar to CategoryTestProps in ConsoleTest. /// [RedbScheme("Department")] public class DepartmentProps { /// Department name (e.g. "IT Department Moscow"). public string Name { get; set; } = string.Empty; /// Description (e.g. "Software development team"). public string Description { get; set; } = string.Empty; /// Is department active? public bool IsActive { get; set; } = true; /// Budget in USD. public decimal Budget { get; set; } /// Department code (e.g. "IT-MSK-DEV"). public string Code { get; set; } = string.Empty; } /// /// City props for list examples (linked objects). /// Used as target object for RedbListItem.Object reference. /// [RedbScheme("City")] public class CityProps { /// City name. public string Name { get; set; } = string.Empty; /// Population count. public int Population { get; set; } /// Region or district. public string Region { get; set; } = string.Empty; /// Is capital city? public bool IsCapital { get; set; } /// GPS coordinates [lat, lon]. public double[] Coordinates { get; set; } = []; } /// /// Person props demonstrating ListItem fields. /// Shows single ListItem and List of ListItems usage. /// [RedbScheme("Person")] public class PersonProps { /// Person name. public string Name { get; set; } = string.Empty; /// Age in years. public int Age { get; set; } /// Email address. public string Email { get; set; } = string.Empty; /// Single ListItem field (e.g. status from dictionary). public RedbListItem? Status { get; set; } /// Array of ListItems (e.g. roles from dictionary). public List? Roles { get; set; } } /// /// Product with a unique business key (V4 [RedbUnique]): the SKU is unique per scheme, /// enforced by the database over the hash of the canonical value. Used by E003. /// public class ProductProps { /// Unique business key. NULL never participates in uniqueness. [RedbUnique] public string? Sku { get; set; } /// Display name (not unique). public string Title { get; set; } = string.Empty; /// Price in USD. public decimal Price { get; set; } } Path: redb/redb.Examples/Models/ExampleResultProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Models/ExampleResultProps.cs ---- using redb.Core.Attributes; namespace redb.Examples.Models; /// /// Platform-specific test result (Count, Time, Status). /// Used as value in Dictionary for each platform. /// public class PlatformResult { /// Number of objects processed/found. public int? Count { get; set; } /// Execution time in milliseconds. public int? Time { get; set; } /// Status: "OK", "FAIL", or error message. public string? Status { get; set; } /// Database round trips the example made. public int? Queries { get; set; } } /// /// Props for storing example test results in redb database. /// Key (E001, E002...) stored in RedbObject._value_string. /// Title stored in RedbObject._name. /// [RedbScheme("ExampleResult")] public class ExampleResultProps { /// License tier: "Free", "Pro", "Enterprise". public string Tier { get; set; } = string.Empty; /// /// Results by platform: "mssql", "mssql.pro", "postgres", "postgres.pro". /// Each platform has Count, Time, Status. /// public Dictionary? Results { get; set; } } Path: redb/redb.Examples/Models/ExampleRunProps.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Models/ExampleRunProps.cs ---- namespace redb.Examples.Models; /// /// One timed pass of one example in one run, kept in the results database as a child of the example's /// object. holds only the latest /// pass per platform; these objects keep every run, so the times can be laid out over runs. /// /// /// No [RedbScheme] attribute on purpose: start-up syncs every attributed scheme into the database it /// opens, and this scheme belongs to the results database only. It is synced there explicitly /// () and lives under its full type name. /// public class ExampleRunProps { /// Example id without the twin suffix: E015 for both E015 and E015_ef. public string ExampleId { get; set; } = string.Empty; /// "redb" or "ef". public string Engine { get; set; } = string.Empty; /// "Pro" or "Free" for redb; null for EF Core. public string? Edition { get; set; } /// "postgres", "sqlite" or "mssql". public string Provider { get; set; } = string.Empty; /// The Pro planner (EnablePvtPrefilter) of the run; null for redb Free and EF Core. public bool? Planner { get; set; } /// "first", "repeat" or "cache". public string Pass { get; set; } = string.Empty; /// The platform key of the pass, the key it has in . public string Platform { get; set; } = string.Empty; /// The example's measured time in milliseconds; null when the engine cannot do the example. public long? TimeMs { get; set; } /// Rows (objects) the example returned or processed, when the example reports it. public int? Count { get; set; } /// Database round trips the example made. public int? Queries { get; set; } /// "OK", "N/A: reason" or the error. public string? Status { get; set; } /// Start of the run (UTC), the same for every pass of the run. public DateTimeOffset RunAt { get; set; } /// Id of the run, the same for every pass of the run. public Guid RunId { get; set; } /// Version of the engine: redb for redb passes, EF Core for EF passes. public string? Version { get; set; } } Path: redb/redb.Examples/Output/ExampleResult.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Output/ExampleResult.cs ---- namespace redb.Examples.Output; /// /// License tier for examples. /// public enum ExampleTier { Free = 0, Pro = 1, Enterprise = 2 } /// /// Result of running an example. Used for unified output. /// public record ExampleResult { /// Example ID (E001, E010). public required string Id { get; init; } /// Example title. public required string Title { get; init; } /// License tier. public required ExampleTier Tier { get; init; } /// Success flag. public required bool Success { get; init; } /// Execution time in milliseconds. public required long ElapsedMs { get; init; } /// Number of objects processed/found. public int? Count { get; init; } /// Short output lines (2-3 max). public required string[] Output { get; init; } /// Generated SQL (if ToSqlStringAsync was called). public string? Sql { get; init; } /// Error message if failed. public string? Error { get; init; } /// Database round trips the example made; filled by the runner, null when not counted. public int? Queries { get; init; } /// /// The library cannot do this out of the box (an EF twin of a window-function or recursive-tree example). /// Not a failure: the reason is in , there is no time to compare. /// public bool NotSupported { get; init; } /// /// The example did no work in this run (a seeding example inside the whole-suite sweep). Such a result /// is not stored, so the time of the last real run stays in the results database. /// public bool Skipped { get; init; } } Path: redb/redb.Examples/Output/ExampleRunLog.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Output/ExampleRunLog.cs ---- using System.Reflection; using Microsoft.EntityFrameworkCore; using redb.Core; using redb.Core.Models.Entities; using redb.Examples.Models; namespace redb.Examples.Output; /// /// The run history of the examples: every pass of every example in every run, stored in the results database as /// objects under the example's object. /// public static class ExampleRunLog { /// /// One per stored pass of . A skipped result is left out, /// as it is left out of . /// /// The passes of the run under their platform keys (postgres.pro, sqlite.pro.cache, postgres.ef.repeat...). /// Start of the run. /// Id of the run. /// The Pro planner setting of the run (EnablePvtPrefilter), recorded on redb Pro passes only. public static List Build( IEnumerable<(string Platform, ExampleResult Result)> runs, DateTimeOffset runAt, Guid runId, bool planner) { var redbVersion = VersionOf(typeof(IRedbService)); var efVersion = VersionOf(typeof(DbContext)); var rows = new List(); foreach (var (platform, result) in runs.Where(r => !r.Result.Skipped)) { // platform key: [.pro|.ef][.repeat|.cache] var parts = platform.Split('.'); var isEf = parts.Length > 1 && parts[1] == "ef"; var isPro = parts.Length > 1 && parts[1] == "pro"; var pass = parts.Length > 1 && parts[^1] is "repeat" or "cache" ? parts[^1] : "first"; rows.Add(new ExampleRunProps { ExampleId = result.Id.EndsWith("_ef", StringComparison.OrdinalIgnoreCase) ? result.Id[..^3] : result.Id, Engine = isEf ? "ef" : "redb", Edition = isEf ? null : isPro ? "Pro" : "Free", Provider = parts[0], Planner = isPro ? planner : null, Pass = pass, Platform = platform, TimeMs = result.NotSupported ? null : result.ElapsedMs, Count = result.Count, Queries = result.Queries, Status = result.NotSupported ? $"N/A: {result.Output.FirstOrDefault()}" : result.Success ? "OK" : (result.Error ?? "FAIL"), RunAt = runAt, RunId = runId, Version = isEf ? efVersion : redbVersion }); } return rows; } /// /// Saves the passes of the run in one batch, each under the result object of its example. The result objects /// must be saved already (they carry their ids). /// /// The results database. /// The example result objects by example id (E015). /// The passes of the run. /// Start of the run. /// Id of the run. /// The Pro planner setting of the run. public static async Task SaveAsync( IRedbService resultsDb, IReadOnlyDictionary> resultByKey, IEnumerable<(string Platform, ExampleResult Result)> runs, DateTimeOffset runAt, Guid runId, bool planner) { var rows = Build(runs, runAt, runId, planner); if (rows.Count == 0) return; await resultsDb.SyncSchemeAsync(); var objects = rows.Select(row => new RedbObject { Name = $"{row.ExampleId} {row.Platform}", ParentId = resultByKey[row.ExampleId].Id, ValueDatetime = row.RunAt, Props = row }).ToList(); await resultsDb.SaveAsync(objects); Console.WriteLine($"Run history saved: {objects.Count} pass(es), run {runId:N} at {runAt:u}"); } private static string VersionOf(Type type) => type.Assembly.GetCustomAttribute()?.InformationalVersion.Split('+')[0] ?? type.Assembly.GetName().Version?.ToString() ?? "?"; } Path: redb/redb.Examples/Output/TablePrinter.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Output/TablePrinter.cs ---- namespace redb.Examples.Output; /// /// Cell with optional color highlighting. /// public record TableCell(string Text, ConsoleColor? Color = null); /// /// Simple table printer with Unicode box-drawing and color support. /// public class TablePrinter { private readonly int[] _widths; private readonly List _rows = []; private readonly List _separatorAfter = []; // row indices after which to add separator public TablePrinter(params int[] columnWidths) { _widths = columnWidths; } /// /// Add header row. /// public TablePrinter Header(params string[] cells) { _rows.Add(cells.Select(c => new TableCell(c)).ToArray()); _separatorAfter.Add(0); // separator after header return this; } /// /// Add data row with plain strings. /// public TablePrinter Row(params string[] cells) { _rows.Add(cells.Select(c => new TableCell(c)).ToArray()); return this; } /// /// Add data row with colored cells. /// public TablePrinter Row(params TableCell[] cells) { _rows.Add(cells); return this; } /// /// Add row and mark separator after it. /// public TablePrinter RowWithSeparator(params string[] cells) { _rows.Add(cells.Select(c => new TableCell(c)).ToArray()); _separatorAfter.Add(_rows.Count - 1); return this; } /// /// Add separator after last row. /// public TablePrinter Separator() { if (_rows.Count > 0) _separatorAfter.Add(_rows.Count - 1); return this; } /// /// Print table to console with colors. /// public void Print() { Console.WriteLine(TopLine()); for (int i = 0; i < _rows.Count; i++) { PrintDataLine(_rows[i]); if (_separatorAfter.Contains(i) && i < _rows.Count - 1) Console.WriteLine(MidLine()); } Console.WriteLine(BottomLine()); } private string TopLine() => Line('┌', '┬', '┐'); private string MidLine() => Line('├', '┼', '┤'); private string BottomLine() => Line('└', '┴', '┘'); private string Line(char left, char mid, char right) { var parts = _widths.Select(w => new string('─', w + 2)); return $"{left}{string.Join(mid, parts)}{right}"; } private void PrintDataLine(TableCell[] cells) { Console.Write('│'); for (int i = 0; i < _widths.Length; i++) { var cell = i < cells.Length ? cells[i] : new TableCell(""); var width = _widths[i]; var text = cell.Text; // Truncate if needed if (text.Length > width) text = text[..(width - 2)] + ".."; Console.Write(' '); // Apply color if specified if (cell.Color.HasValue) { var prev = Console.ForegroundColor; Console.ForegroundColor = cell.Color.Value; Console.Write(text.PadRight(width)); Console.ForegroundColor = prev; } else { Console.Write(text.PadRight(width)); } Console.Write(" │"); } Console.WriteLine(); } } Path: redb/redb.Examples/Program.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/Program.cs ---- using System.Reflection; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Npgsql; using Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure; using redb.Examples.Ef; using redb.Examples.ExamplesEf; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.SQLite.Pro.Extensions; // UseSqlite is tier-agnostic: AddRedb -> Free, AddRedbPro -> Pro // (do NOT also import redb.SQLite.Extensions — its UseSqlite // would make the call ambiguous; switch tiers via AddRedb/AddRedbPro) using redb.SQLite.Data; // SqliteDataSource.NativeExtensionPath (Free native ext) using redb.Examples.Examples; using redb.Examples.Output; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Models.Security; using redb.Postgres; using redb.Core.Extensions; using redb.MSSql.Pro.Extensions; using redb.Postgres.Providers; using redb.Core.Providers; using redb.Core.Serialization; using redb.Examples.Models; using System; using System.Linq; using System.Threading.Tasks; namespace redb.Examples; class Program { /// /// Results storage, a SQLite file of its own (created on first use), whatever provider the examples run /// on: one object per example, every platform and pass of every run under its key, so results of /// different runs and databases sit side by side. /// private const string ResultsConnection = "Data Source=redb_examples_results.db"; static async Task Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; var services = new ServiceCollection(); ConfigureServices(services); await using var provider = services.BuildServiceProvider(); // One scope per unit of work. An IRedbService is one connection: a service kept for the life of the process // cannot serve parallel flows (a web request, a job, a message handler each resolve their own from a scope). // A console does its work in one flow, so the scope here only shows the shape that carries over to hosts. await using var scope = provider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // Get DB type and platform key var ctxName = redb.Context.GetType().Name; var dbType = ctxName.Contains("Npgsql") ? "PostgreSQL" : ctxName.Contains("Sqlite") ? "SQLite" // check before "Sql": "Sqlite".Contains("Sql") == true : "SQL Server"; var platformKey = GetPlatformKey(redb); // --results [--platform ] [E...]: print the saved results and run nothing. The platform decides which // passes come first and what EF is compared with; by default the configured provider's, as in a run. if (args.Contains("--results", StringComparer.OrdinalIgnoreCase)) { var platformAt = Array.FindIndex(args, a => a.Equals("--platform", StringComparison.OrdinalIgnoreCase)); if (platformAt >= 0 && platformAt + 1 < args.Length) platformKey = args[platformAt + 1].ToLowerInvariant(); var requested = args.Where(a => a.StartsWith('E') || a.StartsWith('e')).Select(a => BaseId(a.ToUpperInvariant())).ToHashSet(); Console.WriteLine($"Saved results ({ResultsConnection}) | Platform: {platformKey}"); await WithResultsDbAsync(resultsDb => PrintSavedResultsAsync(resultsDb, requested.Count > 0 ? requested : null, platformKey)); return; } Console.WriteLine($"DB: {dbType} | Platform: {platformKey} | redb.Examples"); Console.WriteLine($"redb {VersionOf(typeof(IRedbService))} | EF Core {VersionOf(typeof(DbContext))} | " + $"Npgsql EF {VersionOf(typeof(NpgsqlDbContextOptionsBuilder))} | Npgsql {VersionOf(typeof(NpgsqlConnection))}"); Console.WriteLine(); // Initialize REDB for tests Console.WriteLine("=== REDB INITIALIZATION ==="); var initSw = System.Diagnostics.Stopwatch.StartNew(); await redb.InitializeAsync(ensureCreated:true); initSw.Stop(); Console.WriteLine($"Initialization complete: {initSw.ElapsedMilliseconds} ms"); Console.WriteLine(); // Discover examples var examples = DiscoverExamples(); // Parse args (stray "-" tokens tolerated: `dotnet run --no-build - E203` forwards the // lone dash to the app) var exampleIds = args.Length > 0 ? args.Select(a => a.ToUpperInvariant()).Where(a => a.StartsWith('E')).ToHashSet() : null; if (exampleIds is { Count: 0 }) exampleIds = null; // Examples that behave differently when asked for by name (E203 seeds only then). ExampleBase.ExplicitlyRequestedIds = exampleIds; // redb examples and their EF Core twins (*_ef). Naming an example runs its twin with it; naming a // twin runs the twin alone (E203_ef seeds the flat database by itself). bool Selected(ExampleMetaAttribute meta) => exampleIds == null || exampleIds.Contains(meta.Id.ToUpperInvariant()) || exampleIds.Contains(BaseId(meta.Id).ToUpperInvariant()); var redbToRun = examples.Where(e => e.example is not EfExampleBase && Selected(e.meta!)).ToList(); var efToRun = examples.Where(e => e.example is EfExampleBase && Selected(e.meta!)).ToList(); // The EF twins work on the flat PostgreSQL database only: next to redb on another provider their // numbers would compare different databases, so they do not run. if (efToRun.Count > 0 && !RunsOnEfProvider(platformKey)) { Console.WriteLine($"EF Core twins skipped: they run on PostgreSQL only ({EfPlatformKey}), redb runs on {platformKey}."); Console.WriteLine(); efToRun.Clear(); } if (redbToRun.Count == 0 && efToRun.Count == 0) { Console.WriteLine("No examples to run. Available:"); foreach (var (ex, meta) in examples.Where(e => e.meta != null)) Console.WriteLine($" {meta!.Id} - {meta.Title} [{meta.Tier}]"); return; } // EF Core twins work on the flat database. Like redb.InitializeAsync above, the EF model is built // and a pooled connection opened here, before any example is timed. Only when a twin is selected, // so a redb-only run does not need the flat database. if (efToRun.Count > 0) { var efContexts = scope.ServiceProvider.GetRequiredService>(); EfExampleBase.Contexts = efContexts; Console.WriteLine("=== EF CORE INITIALIZATION ==="); var efInitSw = System.Diagnostics.Stopwatch.StartNew(); await using (var warm = await efContexts.CreateDbContextAsync()) { _ = warm.Model; await warm.Database.OpenConnectionAsync(); await warm.Database.CloseConnectionAsync(); } efInitSw.Stop(); Console.WriteLine($"EF Core initialization complete: {efInitSw.ElapsedMilliseconds} ms"); Console.WriteLine(); } // Round trips are counted on both sides: redb through its ActivitySource, EF through an interceptor. CommandCounters.StartRedb(); var efKey = EfPlatformKey; var runs = new List<(string Platform, ExampleResult Result)>(); var runAt = DateTimeOffset.UtcNow; var runId = Guid.NewGuid(); // Pass 1: redb, default settings. Pass 2: EF Core. await RunPassAsync(platformKey, redbToRun, redb, () => CommandCounters.Redb, runs); await RunPassAsync(efKey, efToRun, redb, () => CommandCounters.Ef, runs); // Passes 3 to 5 repeat the same examples. Setup examples (seeding, bulk insert) are not repeated: // they would only add the same data again. var redbRepeat = redbToRun.Where(e => e.meta!.Category != "Setup").ToList(); var efRepeat = efToRun.Where(e => e.meta!.Category != "Setup").ToList(); if (redbRepeat.Count > 0) { // redb with the props cache: a service of its own, initialized outside the measurement. Its // first pass is a repeat that fills the cache, its second pass reads through it. var cacheServices = new ServiceCollection(); ConfigureServices(cacheServices, enablePropsCache: true); await using var cacheProvider = cacheServices.BuildServiceProvider(); await using var cacheScope = cacheProvider.CreateAsyncScope(); var cachedRedb = cacheScope.ServiceProvider.GetRequiredService(); await cachedRedb.InitializeAsync(); await RunPassAsync($"{platformKey}.repeat", redbRepeat, cachedRedb, () => CommandCounters.Redb, runs); await RunPassAsync($"{platformKey}.cache", redbRepeat, cachedRedb, () => CommandCounters.Redb, runs); } await RunPassAsync($"{efKey}.repeat", efRepeat, redb, () => CommandCounters.Ef, runs); Console.WriteLine(); // The direct table of the run, kept for reference; the results now come from the results database. // PrintResults(runs.Where(r => r.Platform == platformKey).Select(r => r.Result).ToList()); // Save results to the separate results database and print them from there await WithResultsDbAsync(async resultsDb => { await SaveResultsAsync(resultsDb, runs, runAt, runId, redb.Configuration.EnablePvtPrefilter); await PrintSavedResultsAsync(resultsDb, runs.Select(r => BaseId(r.Result.Id)).ToHashSet(), platformKey); }); } /// Opens the results storage (, created on first use) for one unit of work. private static async Task WithResultsDbAsync(Func work) { var resultsServices = new ServiceCollection(); resultsServices.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); resultsServices.AddRedbPro(options => options.UseSqlite(ResultsConnection)); await using var resultsProvider = resultsServices.BuildServiceProvider(); await using var resultsScope = resultsProvider.CreateAsyncScope(); var resultsDb = resultsScope.ServiceProvider.GetRequiredService(); await resultsDb.InitializeAsync(ensureCreated: true); await work(resultsDb); } /// /// Runs one pass over and adds each result, with the round trips it made, to /// under . /// private static async Task RunPassAsync( string platform, List<(ExampleBase example, ExampleMetaAttribute? meta)> toRun, IRedbService redb, Func commands, List<(string Platform, ExampleResult Result)> runs) { if (toRun.Count == 0) return; Console.WriteLine($"=== PASS {platform} ==="); var current = 0; foreach (var (example, meta) in toRun.OrderBy(e => e.meta?.Id)) { if (meta == null) continue; current++; // Progress indicator Console.Write($"[{current}/{toRun.Count}] {meta.Id} {meta.Title}..."); var before = commands(); try { var result = await example.RunAsync(redb); runs.Add((platform, result with { Queries = result.NotSupported ? null : (int)(commands() - before) })); Console.WriteLine(result.Skipped ? " SKIPPED" : result.NotSupported ? " N/A" : result.Success ? " OK" : " FAIL"); } catch (Exception ex) { runs.Add((platform, new ExampleResult { Id = meta.Id, Title = meta.Title, Tier = meta.Tier, Success = false, ElapsedMs = 0, Output = [], Error = ex.Message })); Console.WriteLine($" ERROR: {ex.Message}"); } } Console.WriteLine(); } /// The id of the redb example a twin belongs to: E010_ef gives E010. private static string BaseId(string id) => IsTwin(id) ? id[..^3] : id; private static bool IsTwin(string id) => id.EndsWith("_ef", StringComparison.OrdinalIgnoreCase); /// /// Platform key of the EF Core passes. The EF context works on the flat PostgreSQL database /// () whatever provider redb runs on, so the key names that database. /// private const string EfPlatformKey = "postgres.ef"; /// /// The kind of a pass from its platform key: first for postgres.pro or postgres.ef, /// otherwise the last part (repeat, cache). /// private static string PassKind(string platformKey) { var parts = platformKey.Split('.'); return parts.Length > 2 ? parts[^1] : "first"; } /// Whether redb runs on the provider of the EF twins, so that the two sides are comparable. private static bool RunsOnEfProvider(string platformKey) => platformKey.StartsWith("postgres.", StringComparison.OrdinalIgnoreCase); /// /// The flat database of the EF Core twins (redb.Export/doc/PLAN_EF_BENCHMARK.md): the schema from /// `redb flat --ddl-only`, the data seeded by EF itself (E203_ef). Same server and session options as /// the redb database below, so both sides run under the same settings. /// private const string FlatEfConnection = "Host=127.0.0.1;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_examples_flat_ef;Pooling=true;Timeout=600;Command Timeout=600;Include Error Detail=true;Options=-c jit=off"; /// Product version of the assembly that defines , without the commit suffix. private static string VersionOf(Type type) => type.Assembly.GetCustomAttribute()?.InformationalVersion.Split('+')[0] ?? type.Assembly.GetName().Version?.ToString() ?? "?"; /// Container to fill. /// Turns redb's props cache on: the pass that shows what the cache gives. private static void ConfigureServices(ServiceCollection services, bool enablePropsCache = false) { // EF Core side: a context factory, so every EF unit of work gets a new context, as EF recommends. // The interceptor only counts round trips for the comparison table. services.AddDbContextFactory(options => options .UseNpgsql(FlatEfConnection) .AddInterceptors(CommandCounters.EfInterceptor)); services.AddLogging(b => b .AddConsole() .SetMinimumLevel(LogLevel.Warning)); // FREE SQLite needs the native extension loaded on every connection (it hosts // get_object_json / pvt_build_*_sql in-DB). Make the example run out-of-the-box: // honor REDB_SQLITE_EXTENSION if it's set (that's the env default), otherwise // locate redb.SQLite/native/build/redbsqlite.{dll,so,dylib} by walking up from the app // base dir. (Harmless for the Pro run — Pro never calls those functions.) SqliteDataSource.NativeExtensionPath ??= ResolveSqliteNativeExtension(); // SQLite reads through a 2 MB page cache per connection by default; on the seeded examples // database (2.5 GB) that is what most of a query's time goes into. Map the file instead, // and give each connection a moderate cache on top of the mapping. SqliteDataSource.MmapSizeBytes = 4L * 1024 * 1024 * 1024; SqliteDataSource.CacheSizeBytes = 64L * 1024 * 1024; // Pro is free: no license key is required. An empty string means no key. services.AddRedbPro(options => options .Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; // Pro run. FREE tier: DeleteInsert (ChangeTracking is a Pro feature). //c.SkipHashValidationOnCacheCheck = false; c.EnablePropsCache = enablePropsCache; c.PropsCacheMaxSize = 100000; //c.PropsCacheTtl = TimeSpan.FromMinutes(60); // PVT prefilter (Pro + PostgreSQL, opt-in). Flip to true and re-run E202 to // diff the SQL with and without the cutting step. See docs/PVT_PREFILTER_PLAN.md. c.EnablePvtPrefilter = true;// Environment.GetEnvironmentVariable("REDB_PVT_PREFILTER") == "1"; }) // Examples live in their OWN databases (redb_examples), never in the test/Identity // `redb`: the integration-test fixtures wipe their database CLEAN on start, and a // seeded 8M-row _values under the cascade trigger turns that wipe into hours // (2026-09-10: a seeded database was lost to exactly this). //.UsePostgres("Host=127.0.0.1;Port=5432;Username=postgres;Password=YOUR_PASSWORD;Database=redb_examples;Pooling=true;Timeout=600;Command Timeout=600;Include Error Detail=true;Options=-c jit=off") //.UseMsSql("Server=127.0.0.1,1433;Database=redb_examples;User Id=sa;Password=YOUR_PASSWORD;TrustServerCertificate=true;Command Timeout=600;") // 127.0.0.1 (not localhost): localhost->::1 hits docker [::]:1433 and hangs ~63s .UseSqlite(@"Data Source=redb_examples.db") ); } /// /// Locate the FREE SQLite native extension (redbsqlite.dll/.so/.dylib) by walking up the /// directory tree from the running app to the repo's redb.SQLite/native/build folder. /// Returns the full path (suffix included) or null if not found / not yet built. /// private static string? ResolveSqliteNativeExtension() { var suffix = OperatingSystem.IsWindows() ? ".dll" : OperatingSystem.IsMacOS() ? ".dylib" : ".so"; for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent) { // Public mirror layout first (redb.SQLite at the top level), then the development repository layout (redb.DB/src). var candidate = Path.Combine(dir.FullName, "redb.SQLite", "native", "build", "redbsqlite" + suffix); if (!File.Exists(candidate)) candidate = Path.Combine(dir.FullName, "redb.DB", "src", "redb.SQLite", "native", "build", "redbsqlite" + suffix); if (File.Exists(candidate)) return candidate; } Console.WriteLine( "[WARN] FREE SQLite native extension not found (redb.SQLite/native/build/redbsqlite" + suffix + "). Build it (cmake --build redb.SQLite/native/build) or set REDB_SQLITE_EXTENSION. " + "Without it, get_object_json / pvt_build_*_sql are missing and most examples FAIL."); return null; } private static List<(ExampleBase example, ExampleMetaAttribute? meta)> DiscoverExamples() { return Assembly.GetExecutingAssembly() .GetTypes() .Where(t => t.IsSubclassOf(typeof(ExampleBase)) && !t.IsAbstract) .Select(t => ( example: (ExampleBase)Activator.CreateInstance(t)!, meta: t.GetCustomAttribute() )) .Where(e => e.meta != null) .OrderBy(e => e.meta!.Id) .ToList(); } /// /// Determines current platform key based on database type and Pro/Free version. /// private static string GetPlatformKey(IRedbService redb) { var ctxName = redb.Context.GetType().Name; var isPro = redb.GetType().Assembly.FullName?.Contains(".Pro") == true; var db = ctxName.Contains("Npgsql") ? "postgres" : ctxName.Contains("Sqlite") ? "sqlite" // check before "Sql": "Sqlite".Contains("Sql") == true : "mssql"; return isPro ? $"{db}.pro" : db; } /// /// Saves or updates the results of this run in the results database, one object per example: its /// key (E001, E002...) in ValueString, its title in Name, every pass under its platform key. An EF /// twin (E010_ef) is stored with its redb example (E010), under the EF platform key, so both sides /// sit in one object. Other platforms already stored for an example are kept. /// private static async Task SaveResultsAsync(IRedbService redb, List<(string Platform, ExampleResult Result)> runs, DateTimeOffset runAt, Guid runId, bool planner) { Console.WriteLine(); Console.WriteLine("=== SAVING RESULTS ==="); // Load all existing results at once (with Props) var existingResults = await redb.Query() .ToListAsync(); var existingByKey = existingResults.ToDictionary(r => r.ValueString ?? "", r => r); var toSave = new List>(); var saved = 0; var updated = 0; // A skipped result (a seeding example inside the whole-suite sweep) is not stored: the time of the // last real seed stays. foreach (var example in runs.Where(r => !r.Result.Skipped).GroupBy(r => BaseId(r.Result.Id))) { // Title and tier come from the redb example when it ran, from the twin otherwise. var lead = example.FirstOrDefault(r => !IsTwin(r.Result.Id)).Result ?? example.First().Result; var title = IsTwin(lead.Id) && lead.Title.StartsWith("EF: ", StringComparison.Ordinal) ? lead.Title[4..] : lead.Title; var tierString = lead.Tier switch { ExampleTier.Free => "Free", ExampleTier.Pro => "Pro", ExampleTier.Enterprise => "Enterprise", _ => "Free" }; if (!existingByKey.TryGetValue(example.Key, out var target)) { target = new RedbObject { Name = title, ValueString = example.Key, Props = new ExampleResultProps() }; existingByKey[example.Key] = target; saved++; } else { updated++; } // Update existing object - preserve other platforms! target.Props ??= new ExampleResultProps(); target.Props.Tier = tierString; target.Props.Results ??= new Dictionary(); foreach (var (platform, result) in example) { target.Props.Results[platform] = new PlatformResult { Count = result.Count, Time = result.NotSupported ? null : (int)result.ElapsedMs, Queries = result.Queries, Status = result.NotSupported ? $"N/A: {result.Output.FirstOrDefault()}" : result.Success ? "OK" : (result.Error ?? "FAIL") }; } toSave.Add(target); } // Batch save all at once if (toSave.Count > 0) { await redb.SaveAsync(toSave); await ExampleRunLog.SaveAsync(redb, existingByKey, runs, runAt, runId, planner); } Console.WriteLine($"Results saved: {saved} new, {updated} updated (batch)"); } /// /// Loads the results of the given examples from the results database and prints them, each pass on a /// line of its own: redb, redb with the props cache, EF Core. An EF line also shows how its time /// compares with redb's (EF against the first redb pass, EF repeat against redb with the cache). /// private static async Task PrintSavedResultsAsync(IRedbService redb, IReadOnlySet? exampleKeys, string platformKey) { Console.WriteLine(); Console.WriteLine("=== RESULTS ==="); // exampleKeys null: every saved example. var allResults = (await redb.Query() .OrderByRedb(r => r.ValueString) .ToListAsync()) .Where(r => r.ValueString != null && (exampleKeys == null || exampleKeys.Contains(r.ValueString))) .ToList(); if (allResults.Count == 0) { Console.WriteLine("No saved results in database."); return; } // Passes of this platform first, in the order they run; whatever else an example carries after. var efKey = EfPlatformKey; var order = new[] { platformKey, $"{platformKey}.repeat", $"{platformKey}.cache", efKey, $"{efKey}.repeat" }; // The ratio to EF only where redb ran on the same provider. var compareWithEf = RunsOnEfProvider(platformKey); // Table with platforms as subrows for easy comparison // No TIER column: the tier is redb's licence tier and says nothing about an EF line. var table = new TablePrinter(8, 44, 8, 10, 7, 50); table.Header("ID", "TITLE", "COUNT", "TIME", "SQL", "PLATFORM: STATUS"); for (int i = 0; i < allResults.Count; i++) { var r = allResults[i]; var id = r.ValueString ?? "-"; var title = r.Name ?? "-"; var platforms = r.Props?.Results ?? new Dictionary(); // First row: ID, Title table.Row( new TableCell(id), new TableCell(title), new TableCell(""), new TableCell(""), new TableCell(""), new TableCell("") ); // The fastest and the slowest within each kind of pass (first, repeat, cache), across providers and // libraries: yellow and red. A cold first pass is never set against a pass over a warm cache. var best = new HashSet(); var worst = new HashSet(); var byKind = platforms .Where(p => p.Value.Time is > 0 && p.Value.Status?.StartsWith("OK", StringComparison.Ordinal) == true) .GroupBy(p => PassKind(p.Key)); foreach (var kind in byKind.Where(g => g.Count() > 1)) { best.Add(kind.MinBy(p => p.Value.Time)!.Key); worst.Add(kind.MaxBy(p => p.Value.Time)!.Key); } // Platform subrows foreach (var platform in order.Where(platforms.ContainsKey).Concat(platforms.Keys.Except(order).Order())) { var pr = platforms[platform]; var count = pr.Count?.ToString() ?? "-"; var time = pr.Time != null ? $"{pr.Time}ms" : "-"; var queries = pr.Queries?.ToString() ?? "-"; var status = pr.Status ?? "-"; // EF against redb pass for pass: the first EF pass against the first redb pass, the EF repeat // against the redb repeat. var against = !compareWithEf ? null : platform == efKey ? platformKey : platform == $"{efKey}.repeat" ? $"{platformKey}.repeat" : null; if (against != null && pr.Time is > 0 && platforms.GetValueOrDefault(against)?.Time is > 0 and var redbTime) { // The pass without the provider prefix keeps the line inside the column; a ratio below 1 // keeps two decimals, so a fast EF line does not print as x0.0. var ratio = (double)pr.Time.Value / redbTime; var pass = against[(against.IndexOf('.') + 1)..]; status += $" x{ratio.ToString(ratio < 1 ? "F2" : "F1")} vs {pass}"; } var color = status.StartsWith("N/A", StringComparison.Ordinal) ? ConsoleColor.DarkYellow : !status.StartsWith("OK", StringComparison.Ordinal) ? ConsoleColor.Red : best.Contains(platform) ? ConsoleColor.Yellow : worst.Contains(platform) ? ConsoleColor.Red : ConsoleColor.Green; table.Row( new TableCell(""), new TableCell(""), new TableCell(count, color), new TableCell(time, color), new TableCell(queries, color), new TableCell($" {platform,-20}: {status}", color) ); } // Separator between examples (except last) if (i < allResults.Count - 1) table.Separator(); } Console.WriteLine(); table.Print(); // Summary by platform Console.WriteLine(); foreach (var platform in allResults.SelectMany(r => r.Props?.Results?.Keys ?? Enumerable.Empty()).Distinct() .OrderBy(p => Array.IndexOf(order, p) is var index and >= 0 ? index : int.MaxValue).ThenBy(p => p)) { var statuses = allResults.Select(r => r.Props?.Results?.GetValueOrDefault(platform)?.Status).Where(s => s != null).ToList(); var ok = statuses.Count(s => s == "OK"); var notSupported = statuses.Count(s => s!.StartsWith("N/A", StringComparison.Ordinal)); var fail = statuses.Count - ok - notSupported; Console.WriteLine($" {platform,-20}: {ok} OK, {fail} FAIL, {notSupported} N/A (of {statuses.Count})"); } PrintAverageHistogram(allResults); } /// /// Average time per platform as a bar chart, fastest first. Only the examples every platform finished with /// OK and a time count, so each average is taken over the same set of tasks. /// private static void PrintAverageHistogram(List> results) { static bool Timed(PlatformResult? pr) => pr?.Time is > 0 && pr.Status?.StartsWith("OK", StringComparison.Ordinal) == true; // A platform takes part when it has a time for at least half of the examples the best covered // platform has. One that ran a few examples only (a single seed run) would otherwise leave // no example common to all; it is named below the charts instead. var timedExamples = results.SelectMany(r => r.Props?.Results ?? Enumerable.Empty>()) .Where(p => Timed(p.Value)) .GroupBy(p => p.Key) .ToDictionary(g => g.Key, g => g.Count()); var widest = timedExamples.Count > 0 ? timedExamples.Values.Max() : 0; var platforms = timedExamples.Where(p => p.Value * 2 >= widest).Select(p => p.Key).ToList(); var leftOut = results.SelectMany(r => r.Props?.Results?.Keys ?? Enumerable.Empty()).Distinct() .Except(platforms).Order().ToList(); var common = results .Where(r => r.Props?.Results is { } byPlatform && platforms.All(p => Timed(byPlatform.GetValueOrDefault(p)))) .ToList(); if (common.Count == 0) { Console.WriteLine(); Console.WriteLine("=== AVERAGE TIME ==="); Console.WriteLine(" No example was finished by every platform."); return; } var times = platforms.ToDictionary(p => p, p => common.Select(r => (double)r.Props!.Results![p].Time!.Value).Order().ToList()); // The mean follows the heavy examples (seeding, bulk inserts); the median shows the typical one. PrintBars($"AVERAGE TIME, fastest first ({common.Count} examples finished by every platform)", times.Select(t => (t.Key, t.Value.Average()))); PrintBars($"MEDIAN TIME, fastest first (same {common.Count} examples)", times.Select(t => (t.Key, Median(t.Value)))); if (leftOut.Count > 0) { Console.WriteLine(); Console.WriteLine($" Not in the charts (too few examples with a time): {string.Join(", ", leftOut)}"); } } /// The middle value of an ordered list; the mean of the two middle values when the count is even. private static double Median(List ordered) => ordered.Count % 2 == 1 ? ordered[ordered.Count / 2] : (ordered[ordered.Count / 2 - 1] + ordered[ordered.Count / 2]) / 2; /// One bar per platform, shortest first: the fastest yellow, the slowest red. private static void PrintBars(string title, IEnumerable<(string Platform, double Ms)> values) { var sorted = values.OrderBy(v => v.Ms).ToList(); Console.WriteLine(); Console.WriteLine($"=== {title} ==="); const int barWidth = 50; var max = sorted[^1].Ms; for (var i = 0; i < sorted.Count; i++) { var (platform, ms) = sorted[i]; var bar = new string('█', Math.Max(1, (int)Math.Round(ms / max * barWidth))); Console.ForegroundColor = i == 0 ? ConsoleColor.Yellow : i == sorted.Count - 1 ? ConsoleColor.Red : ConsoleColor.Green; Console.WriteLine($" {platform,-20}: {bar} {ms:F0} ms"); Console.ResetColor(); } } private static void PrintResults(List results) { var table = new TablePrinter(6, 50, 6, 6, 10, 8); table.Header("ID", "TITLE", "TIER", "COUNT", "TIME", "STATUS"); var sorted = results.OrderBy(r => r.Id).ToList(); for (int i = 0; i < sorted.Count; i++) { var r = sorted[i]; var tier = r.Tier switch { ExampleTier.Free => "FREE", ExampleTier.Pro => "PRO", _ => "ENT" }; var status = r.Success ? "OK" : "FAIL"; var countVal = r.Count ?? 0; var count = r.Count?.ToString() ?? "-"; // Highlight: red if time > 1000ms or count = 0 var timeColor = r.ElapsedMs > 1000 ? ConsoleColor.Red : (ConsoleColor?)null; var countColor = countVal == 0 ? ConsoleColor.Red : (ConsoleColor?)null; var statusColor = r.Success ? (ConsoleColor?)null : ConsoleColor.Red; table.Row( new TableCell(r.Id), new TableCell(r.Title), new TableCell(tier), new TableCell(count, countColor), new TableCell($"{r.ElapsedMs}ms", timeColor), new TableCell(status, statusColor) ); // Output lines foreach (var line in r.Output.Take(2)) table.Row("", $" {line}", "", "", "", ""); // Error if (!r.Success && r.Error != null) table.Row(new TableCell(""), new TableCell($" ERROR: {r.Error}", ConsoleColor.Red), new TableCell(""), new TableCell(""), new TableCell(""), new TableCell("")); // Separator between examples (except last) if (i < sorted.Count - 1) table.Separator(); } Console.WriteLine(); table.Print(); // Summary var ok = results.Count(r => r.Success); var fail = results.Count(r => !r.Success); var totalMs = results.Sum(r => r.ElapsedMs); Console.WriteLine(); Console.WriteLine($"Results: {ok} OK, {fail} FAIL | Total time: {totalMs}ms"); } } Path: redb/redb.Examples/README.md Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/README.md ---- # REDB Examples Project Public code examples for REDB documentation website. ## Project Structure ``` redb.Examples/ ├── Models/ │ └── ExampleModels.cs # EmployeeProps, ProjectMetricsProps, etc. ├── Examples/ │ ├── ExampleBase.cs # Base class + ExampleMetaAttribute │ ├── E000_BulkInsert.cs # Setup: creates 100 employees (run first!) │ ├── E001_SaveAsync.cs # CRUD examples │ ├── E010_WhereSimple.cs # Query examples │ └── ... ├── Output/ │ ├── ExampleResult.cs # Result record + ExampleTier enum │ └── TablePrinter.cs # Console table formatter └── Program.cs # Entry point, runs all examples ``` ## Data Model All examples use `EmployeeProps` from `Models/ExampleModels.cs`. **DO NOT copy models from redb.ConsoleTest** - we have our own with business-friendly names. ### EmployeeProps Fields | Category | Fields | Notes | |----------|--------|-------| | Basic | FirstName, LastName, Age, Position, Salary, Department, HireDate | Simple types | | Arrays | Skills[], SkillLevels[], Certifications[] | string[], int[] | | Nested | HomeAddress, WorkAddress (with Building) | Business classes | | Contacts | Contacts[] | Array of business classes | | References | CurrentProject, PastProjects[] | RedbObject | | Dictionaries | PhoneDirectory, BonusByYear, OfficeLocations | Various key/value types | | Pro Dict | DepartmentHistory, PerformanceReviews, ProjectMetrics | Complex keys/values | ## Example Format ### 1. Required Attribute ```csharp [ExampleMeta( "E010", // ID: E + 3 digits "Where - Filter by Salary", // Title for website "Query", // Category: CRUD, Query, Trees, Bulk, Dict, etc. ExampleTier.Free, // Tier: Free, Pro, or Enterprise 1, // Difficulty: 1-5 "Where", "Query", "Filter" // Tags for search )] ``` ### 2. Class Structure ```csharp using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Short description of what this example demonstrates. /// [ExampleMeta("E0XX", "Title", "Category", ExampleTier.Free, 1, "Tag1", "Tag2")] public class E0XX_ExampleName : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // YOUR CODE HERE // Use data from E000_BulkInsert (100 employees already exist) // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E0XX", "Title", ExampleTier.Free, sw.ElapsedMilliseconds, [$"Line 1: what query does", $"Result: {result.Count} items"]); } } ``` ### 3. SQL Output Every query example MUST include commented ToSqlStringAsync: ```csharp // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); ``` ## ID Numbering Scheme | Range | Category | Examples | |-------|----------|----------| | **E000-E009** | **Setup/Bulk** | | | E000 | Bulk Insert | Creates 100 employees (run first!) | | E001 | SaveAsync | Create single object | | E002 | LoadAsync | Load by ID | | E003 | DeleteAsync | Delete object | | **E010-E019** | **Where - Basic** | | | E010 | Where simple | `Salary > 75000` | | E011 | Where AND | `Age >= 30 && Salary > 70000` | | E012 | Where OR | `Age < 30 \|\| Salary > 90000` | | E013 | Where NOT | `Position != "Manager"` | | E014 | Where range | `Salary > 60000 && Salary < 90000` | | E015 | Where multiple AND | `A && B && C && D` (3+ conditions) | | E016 | Where chain | `.Where(A).Where(B).Where(C)` | | **E020-E029** | **Where - DateTime** | | | E020 | DateTime equals | `HireDate == specificDate` | | E021 | DateTime greater | `HireDate >= startDate` | | E022 | DateTime range | `HireDate >= start && HireDate < end` | | E023 | DateTime year/month | `.Year == 2024` or `.Month == 6` | | **E030-E039** | **Where - String** | | | E030 | String.Contains | `LastName.Contains("Smith")` | | E031 | String.StartsWith | `FirstName.StartsWith("John")` | | E032 | String.EndsWith | `Email.EndsWith("@company.com")` | | E033 | String equality | `Department == "Engineering"` | | **E040-E049** | **Where - Nested** | | | E040 | Nested property | `HomeAddress.City == "London"` | | E041 | Deep nested | `HomeAddress.Building.Floor > 5` | | E042 | Nested with AND | `HomeAddress.City == "X" && WorkAddress.City == "Y"` | | **E050-E059** | **Arrays (Pro)** | | | E050 | Array.Contains | `Skills.Contains("C#")` | | E051 | Array multiple OR | `Skills.Contains("A") \|\| Skills.Contains("B")` | | E052 | Array NOT Contains | `!Skills.Contains("intern")` | | E053 | Array indexer | `Skills[0] == "C#"` | | E054 | Array + other conditions | `Skills.Contains("X") && Age > 30` | | **E060-E069** | **Dictionaries (Pro)** | | | E060 | Dict ContainsKey | `PhoneDirectory.ContainsKey("desk")` | | E061 | Dict indexer | `PhoneDirectory["desk"] == "x3001"` | | E062 | Dict nested | `OfficeLocations["HQ"].City == "NYC"` | | E063 | Dict key | `PerformanceReviews[(2024, "Q1")]` | | E064 | Dict int key | `BonusByYear[2023] > 5000` | | **E070-E079** | **Aggregates** | | | E070 | CountAsync | Total count | | E071 | CountAsync + Where | Filtered count | | E072 | FirstOrDefaultAsync | First matching | | E073 | AnyAsync | Check existence | | **E080-E089** | **Sorting/Paging** | | | E080 | OrderBy | Sort ascending | | E081 | OrderByDescending | Sort descending | | E082 | ThenBy | Secondary sort | | E083 | Skip/Take | Pagination | | E084 | OrderBy + Where | Sort filtered | | **E090-E099** | **Trees (Pro)** | | | E090 | TreeQuery basics | Get tree structure | | E091 | GetAncestors | Parent chain | | E092 | GetDescendants | All children | | E093 | Tree + Where | Filter in tree | | **E100-E109** | **Advanced** | | | E100 | ChangeTracking | Auto-detect changes | | E101 | Projection | Select specific fields | | E102 | Complex OR+AND | `(A \|\| B) && (C \|\| D)` | | E103 | NOT with nested | `!(A && B)` | ## Tier Guidelines ### Free (ExampleTier.Free) - Basic CRUD: SaveAsync, LoadAsync, DeleteAsync - Simple Where: ==, >, <, AND, OR - Basic sorting: OrderBy, ThenBy - Paging: Skip, Take - CountAsync, FirstOrDefaultAsync ### Pro (ExampleTier.Pro) - Array operations: .Contains(), indexer e.Skills[0] - Dictionary operations: .ContainsKey(), indexer e.Dict["key"] - Complex nested queries: e.HomeAddress.Building.Floor - Bulk operations: SaveAsync(IEnumerable), COPY protocol - Tree queries: TreeQuery, GetAncestors, GetDescendants - Tuple dictionary keys - RedbObject in Dictionary values ## Important Rules 1. **Data source**: All examples use data from E000_BulkInsert (100 employees). Run E000 first, then other examples query existing data. 2. **No test copying**: Do NOT copy tests from redb.ConsoleTest 1:1. Rewrite them as clean, short examples for website display. 3. **Source for ideas**: Look at `redb.ConsoleTest/TestStages/` for what to cover: - Stage13_LinqQueries.cs - basic queries - Stage16_AdvancedLinq.cs - complex queries - Stage17_AdvancedLinqOperators.cs - operators - Stage33_TreeLinqQueries.cs - tree operations - Stage42_BulkInsertPerformanceTest.cs - bulk ops - Stage63_ProExpressionsTest.cs - Pro features - Stage65_ArrayExpressionsTest.cs - array queries 4. **Keep it short**: Examples should be 20-40 lines, not 200. 5. **Meaningful output**: Return 1-2 lines describing what happened: ```csharp [$"Filter: Salary > 75000", $"Found: {result.Count} employees"] ``` 6. **XML Summary**: Add /// summary for parser to extract description. ## Running Examples ```bash # Run all examples dotnet run --project redb.Examples # Run some of them by id dotnet run --project redb.Examples -- E002 E010 E070 # Print the saved results again without running anything dotnet run --project redb.Examples -- --results ``` The database is chosen in `Program.cs` (`ConfigureServices`): one of the `.UsePostgres(...)`, `.UseMsSql(...)`, `.UseSqlite(...)` lines is active, and `AddRedb` / `AddRedbPro` selects the edition. The project starts as Pro; for the Free edition replace `AddRedbPro` with `AddRedb` and set `PropsSaveStrategy` to `DeleteInsert`. Every run stores its results in `redb_examples_results.db`, a SQLite file next to the project, and prints the table from it: one row per example, one line per pass with the time and the number of SQL statements, then the average and the median time per pass as bars. The passes are named by a key: the database (`postgres`, `mssql`, `sqlite`), `.pro` for the Pro edition, `.ef` for EF Core, `.repeat` for the second pass and `.cache` for redb with its props cache. Results of other databases and earlier runs stay in the file, so they sit side by side. ## Comparing with EF Core Each example has an EF Core twin in `ExamplesEf/` (`E010_WhereSimple_ef.cs` next to `E010_WhereSimple.cs`). A twin does the same task with the standard EF Core API over ordinary relational tables: the same classes unfolded by `redb flat`, 54 tables for all models, 41 of them for `EmployeeProps`. The twins run on PostgreSQL only, and only when redb itself runs as Pro on PostgreSQL, so that both sides work on the same server. Where EF Core has no built-in way (window functions, recursive tree queries with a depth), the twin reports `N/A`. To repeat the comparison: ```bash # 1. Two empty databases on your PostgreSQL server: one for redb, one for the flat tables of EF Core createdb redb_examples createdb redb_examples_flat_ef # 2. In Program.cs: AddRedbPro with the .UsePostgres(...) line pointing at redb_examples, # and FlatEfConnection pointing at redb_examples_flat_ef. Then build. dotnet build redb.Examples dotnet build redb.CLI # 3. The flat schema for EF Core: the CLI prints it from the compiled models, psql runs it dotnet run --project redb.CLI --no-build -- flat \ -a redb.Examples/bin/Debug/net10.0/redb.Examples.dll -tp postgres --ddl-only > flat.sql psql -d redb_examples_flat_ef -v ON_ERROR_STOP=1 -1 -f flat.sql # 4. Seed both sides with the same employees (100 000 by default, a reporting tree) dotnet run --project redb.Examples --no-build -- E203 dotnet run --project redb.Examples --no-build -- E203_ef # 5. Run everything: redb, EF Core, the repeats, then the table and the bars dotnet run --project redb.Examples --no-build ``` Notes: - Step 3 comes before any run: as soon as a twin is selected, the program opens the flat database. - In Windows PowerShell 5 the `>` redirect writes UTF-16, which psql does not read: use `| Out-File -Encoding ascii flat.sql` there. PowerShell 7 and bash need nothing. - A seed appends and never clears. `REDB_SEED_COUNT` sets the size (`REDB_SEED_COUNT=2000` for a quick trial) and `REDB_SEED_BATCH` the batch, 1000 by default. With `REDB_SEED_COUNT` set, `E203` seeds its twin as well, and a run of everything seeds again, so unset it after the seed. - The run of everything does not seed and keeps the stored seed times. - `Ef/developer_indexes.sql` holds the indexes a developer would add for the twins' queries; `E203_ef` drops them before the load and creates them again after it, inside its time. - The time of an example is one measured run. Initialization on both sides is outside it. ## Import to Website Examples are parsed by `redb.Doc.Import`: ```bash # Import examples to database dotnet run --project redb.Doc.Import -- --examples # Import everything (docs + examples) dotnet run --project redb.Doc.Import ``` Parser extracts: - Metadata from `[ExampleMeta]` attribute - Description from `/// ` XML comment - Code from `RunAsync` method body ## Template: Free Example ```csharp using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Filter employees by age using Where clause. /// [ExampleMeta("E021", "Where - Filter by Age", "Query", ExampleTier.Free, 1, "Where", "Filter", "Age")] public class E021_WhereAge : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); var query = redb.Query() .Where(e => e.Age >= 30 && e.Age < 40) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E021", "Where - Filter by Age", ExampleTier.Free, sw.ElapsedMilliseconds, [$"Filter: Age 30-39", $"Found: {result.Count} employees"]); } } ``` ## Template: Pro Example ```csharp using System.Diagnostics; using redb.Core; using redb.Examples.Models; using redb.Examples.Output; namespace redb.Examples.Examples; /// /// Query employees by skill using array Contains. /// [ExampleMeta("E040", "Array Contains - Find by Skill", "Query", ExampleTier.Free, 2, "Array", "Contains", "Skills")] public class E040_ArrayContains : ExampleBase { public override async Task RunAsync(IRedbService redb) { var sw = Stopwatch.StartNew(); // Pro: Query array property with Contains var query = redb.Query() .Where(e => e.Skills!.Contains("C#")) .Take(100); // Uncomment to see generated SQL: // var sql = await query.ToSqlStringAsync(); // Console.WriteLine(sql); var result = await query.ToListAsync(); sw.Stop(); return Ok("E040", "Array Contains - Find by Skill", ExampleTier.Free, sw.ElapsedMilliseconds, [$"Filter: Skills contains 'C#'", $"Found: {result.Count} developers"]); } } ``` ## Checklist for New Example - [ ] ID follows numbering scheme (E0XX) - [ ] Title is clear and descriptive - [ ] Category matches content - [ ] Tier is correct (Free vs Pro) - [ ] Tags are relevant for search - [ ] XML summary is present - [ ] Uses data from E000_BulkInsert - [ ] Has commented ToSqlStringAsync - [ ] Output is 1-2 meaningful lines - [ ] Code is under 40 lines ## Links - Documentation (EN): [redbase.app](https://redbase.app) - Documentation (RU): [redb.ru](https://redb.ru) - API Reference: [redbase-app.github.io/redb](https://redbase-app.github.io/redb/) - Examples online (EN): [redbase.app/examples](https://redbase.app/examples) - Examples online (RU): [redb.ru/examples](https://redb.ru/examples) - GitHub: [github.com/redbase-app/redb](https://github.com/redbase-app/redb) Path: redb/redb.Examples/redb.Examples.csproj Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Examples/redb.Examples.csproj ---- Exe net10.0 enable enable redb.Examples.Program all runtime; build; native; contentfiles; analyzers; buildtransitive