Примеры кода

Изучайте RedBase на примерах. Просматривайте рабочие примеры кода для LINQ-запросов, массовых операций, древовидных структур и многого другого.

Data Model - EmployeeProps Нажмите, чтобы увидеть модель данных, используемую во всех примерах
Tag with priority for categorization.
/// <summary>
/// Tag with priority for categorization.
/// </summary>
public class Tag
{
    public string Name { get; set; } = string.Empty;
    public int Priority { get; set; }
    public string? Description { get; set; }
}

/// <summary>
/// Project metrics for analytics.
/// </summary>
[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; }
}

/// <summary>
/// Address with city, street and building details.
/// </summary>
public class Address
{
    public string City { get; set; } = string.Empty;
    public string Street { get; set; } = string.Empty;
    public BuildingInfo? Building { get; set; }
}

/// <summary>
/// Building information with floor and amenities.
/// </summary>
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; }
}

/// <summary>
/// Contact detail key-value pair.
/// </summary>
public class ContactDetail
{
    public string Label { get; set; } = string.Empty;
    public string Value { get; set; } = string.Empty;
}

/// <summary>
/// Contact information (email, phone, etc).
/// </summary>
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; }
}

/// <summary>
/// Department info with tags, metrics and nested budget data.
/// </summary>
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<string, int>? BudgetByYear { get; set; }
}

/// <summary>
/// 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)
/// </summary>
[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<ProjectMetricsProps>? CurrentProject { get; set; }
    public RedbObject<ProjectMetricsProps>[]? PastProjects { get; set; }

    // Phone directory: extension -> phone number
    public Dictionary<string, string>? PhoneDirectory { get; set; }

    // Office locations by city
    public Dictionary<string, Address>? OfficeLocations { get; set; }

    // Bonus history by year
    public Dictionary<int, decimal>? BonusByYear { get; set; }

    // Department details with complex nested data (Pro)
    public Dictionary<string, Department>? 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<string, RedbObject<ProjectMetricsProps>>? ProjectMetrics { get; set; }
}

/// <summary>
/// Department props for tree examples (corporate hierarchy).
/// Used with TreeRedbObject for organizational structure.
/// Similar to CategoryTestProps in ConsoleTest.
/// </summary>
[RedbScheme("Department")]
public class DepartmentProps
{
    /// <summary>Department name (e.g. "IT Department Moscow").</summary>
    public string Name { get; set; } = string.Empty;

    /// <summary>Description (e.g. "Software development team").</summary>
    public string Description { get; set; } = string.Empty;

    /// <summary>Is department active?</summary>
    public bool IsActive { get; set; } = true;

    /// <summary>Budget in USD.</summary>
    public decimal Budget { get; set; }

    /// <summary>Department code (e.g. "IT-MSK-DEV").</summary>
    public string Code { get; set; } = string.Empty;
}

/// <summary>
/// City props for list examples (linked objects).
/// Used as target object for RedbListItem.Object reference.
/// </summary>
[RedbScheme("City")]
public class CityProps
{
    /// <summary>City name.</summary>
    public string Name { get; set; } = string.Empty;
    
    /// <summary>Population count.</summary>
    public int Population { get; set; }
    
    /// <summary>Region or district.</summary>
    public string Region { get; set; } = string.Empty;
    
    /// <summary>Is capital city?</summary>
    public bool IsCapital { get; set; }
    
    /// <summary>GPS coordinates [lat, lon].</summary>
    public double[] Coordinates { get; set; } = [];
}

/// <summary>
/// Person props demonstrating ListItem fields.
/// Shows single ListItem and List of ListItems usage.
/// </summary>
[RedbScheme("Person")]
public class PersonProps
{
    /// <summary>Person name.</summary>
    public string Name { get; set; } = string.Empty;
    
    /// <summary>Age in years.</summary>
    public int Age { get; set; }
    
    /// <summary>Email address.</summary>
    public string Email { get; set; } = string.Empty;
    
    /// <summary>Single ListItem field (e.g. status from dictionary).</summary>
    public RedbListItem? Status { get; set; }
    
    /// <summary>Array of ListItems (e.g. roles from dictionary).</summary>
    public List<RedbListItem>? Roles { get; set; }
}

/// <summary>
/// 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.
/// </summary>
public class ProductProps
{
    /// <summary>Unique business key. NULL never participates in uniqueness.</summary>
    [RedbUnique]
    public string? Sku { get; set; }

    /// <summary>Display name (not unique).</summary>
    public string Title { get; set; } = string.Empty;

    /// <summary>Price in USD.</summary>
    public decimal Price { get; set; }
}

AllAsync - Check All Match

Check if ALL employees match a condition using AllAsync(predicate).
Returns true only if every record satisfies the predicate.
var sw = Stopwatch.StartNew();

// Check if all employees have non-negative salary
var allNonNegativeSalary = await redb.Query<EmployeeProps>()
    .AllAsync(e => e.Salary >= 0);

// Check if all high earners (>100k) are over 25 years old
var allHighEarnersOver25 = await redb.Query<EmployeeProps>()
    .Where(e => e.Salary > 100000m)
    .AllAsync(e => e.Age > 25);

// Negative check: are ALL employees millionaires? (expect false)
var allMillionaires = await redb.Query<EmployeeProps>()
    .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<EmployeeProps>()
    .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);
AllPredicateValidationIRedbQueryable.AllAsync
MS Pro 318ms(3)
mssql.pro.cache 482ms(3)
mssql.pro.repeat 491ms(3)
postgres.ef 103ms(3)
postgres.ef.repeat 88ms(3)
PG Pro 146ms(3)
postgres.pro.cache 143ms(3)
postgres.pro.repeat 143ms(3)
sqlite.pro 143ms(3)
sqlite.pro.cache 151ms(3)
sqlite.pro.repeat 148ms(3)

WhereIn - Filter by List

Filter employees by a list of values using WhereIn.
Equivalent to SQL IN clause - much faster than multiple OR conditions.
var sw = Stopwatch.StartNew();

// Filter by list of departments
var targetDepartments = new[] { "Engineering", "Sales", "Marketing" };
var query = redb.Query<EmployeeProps>()
    .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<EmployeeProps>()
    .WhereIn(e => e.Department, targetDepartments)
    .CountAsync();

sw.Stop();
WhereInINFilterListIRedbQueryable.WhereIn
MS Pro 172ms(60124)
mssql.pro.cache 166ms(60126)
mssql.pro.repeat 152ms(60125)
postgres.ef 983ms(60183)
postgres.ef.repeat 997ms(60184)
PG Pro 107ms(60184)
postgres.pro.cache 39ms(60186)
postgres.pro.repeat 36ms(60185)
sqlite.pro 301ms(60061)
sqlite.pro.cache 237ms(60063)
sqlite.pro.repeat 206ms(60062)

Select - Projection

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.
var sw = Stopwatch.StartNew();

// Server-side projection - fetches only selected Props fields
var query = redb.Query<EmployeeProps>()
    .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";
SelectProjectionFieldsIRedbQueryable.Select
MS Pro 144ms(100)
mssql.pro.cache 150ms(100)
mssql.pro.repeat 159ms(100)
postgres.ef 46ms(100)
postgres.ef.repeat 35ms(100)
PG Pro 108ms(100)
postgres.pro.cache 92ms(100)
postgres.pro.repeat 93ms(100)
sqlite.pro 86ms(100)
sqlite.pro.cache 61ms(100)
sqlite.pro.repeat 61ms(100)

Distinct - Unique by Props

Get unique objects by Props hash using Distinct().
Server-side: SELECT DISTINCT ON (_hash) - deduplicates by Props content.
var sw = Stopwatch.StartNew();

// Server-side Distinct by Props hash
var query = redb.Query<EmployeeProps>()
    .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<EmployeeProps>().CountAsync();

sw.Stop();
DistinctUniqueDedupeIRedbQueryable.Distinct
MS Pro 446ms(100)
mssql.pro.cache 362ms(100)
mssql.pro.repeat 386ms(100)
PG Pro 112ms(100)
postgres.pro.cache 90ms(100)
postgres.pro.repeat 89ms(100)
sqlite.pro 156ms(100)
sqlite.pro.cache 161ms(100)
sqlite.pro.repeat 140ms(100)

OrderBy - Sort by Salary

Sort employees by salary using OrderBy.
Get top 5 lowest and highest earners.
var sw = Stopwatch.StartNew();

// Ascending - lowest earners
var lowest = await redb.Query<EmployeeProps>()
    .OrderBy(e => e.Salary)
    .Take(5)
    .ToListAsync();

// Descending - highest earners
var highest = await redb.Query<EmployeeProps>()
    .OrderByDescending(e => e.Salary)
    .Take(5)
    .ToListAsync();

sw.Stop();

var lowestSalary = lowest.FirstOrDefault()?.Props?.Salary ?? 0;
var highestSalary = highest.FirstOrDefault()?.Props?.Salary ?? 0;
OrderBySort
MS Pro 154ms(10)
mssql.pro.cache 125ms(10)
mssql.pro.repeat 151ms(10)
postgres.ef 1807ms(10)
postgres.ef.repeat 1861ms(10)
PG Pro 152ms(10)
postgres.pro.cache 106ms(10)
postgres.pro.repeat 124ms(10)
sqlite.pro 119ms(10)
sqlite.pro.cache 130ms(10)
sqlite.pro.repeat 126ms(10)

OrderBy + ThenBy

Sort employees by multiple fields using ThenBy.
Sort by department, then by salary descending.
var sw = Stopwatch.StartNew();

var query = redb.Query<EmployeeProps>()
    .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}" : "-";
OrderByThenBySort
MS Pro 155ms(100)
mssql.pro.cache 716ms(100)
mssql.pro.repeat 152ms(100)
postgres.ef 1261ms(100)
postgres.ef.repeat 1240ms(100)
PG Pro 180ms(100)
postgres.pro.cache 129ms(100)
postgres.pro.repeat 178ms(100)
sqlite.pro 229ms(100)
sqlite.pro.cache 232ms(100)
sqlite.pro.repeat 232ms(100)

Skip/Take - Pagination

Paginate employees using Skip and Take.
Get page 2 with 10 items per page.
var sw = Stopwatch.StartNew();

const int pageSize = 10;
const int page = 2; // 0-based would skip 10

var query = redb.Query<EmployeeProps>()
    .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();
SkipTakePagination
MS Pro 152ms(10)
mssql.pro.cache 154ms(10)
mssql.pro.repeat 154ms(10)
postgres.ef 886ms(10)
postgres.ef.repeat 907ms(10)
PG Pro 116ms(10)
postgres.pro.cache 129ms(10)
postgres.pro.repeat 113ms(10)
sqlite.pro 177ms(10)
sqlite.pro.cache 165ms(10)
sqlite.pro.repeat 154ms(10)

OrderByDescending - Reverse Sort

Sort employees in descending order using OrderByDescending.
Get top earners and most experienced employees.
var sw = Stopwatch.StartNew();

// Top earners (highest salary first)
var query = redb.Query<EmployeeProps>()
    .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<EmployeeProps>()
    .OrderByDescending(e => e.Age)
    .Take(5)
    .ToListAsync();

sw.Stop();

var topSalary = topEarners.FirstOrDefault()?.Props?.Salary ?? 0;
var oldestAge = oldest.FirstOrDefault()?.Props?.Age ?? 0;
OrderByDescendingSortDescendingIRedbQueryable.OrderByDescending
MS Pro 149ms(10)
mssql.pro.cache 112ms(10)
mssql.pro.repeat 117ms(10)
postgres.ef 1121ms(10)
postgres.ef.repeat 1236ms(10)
PG Pro 140ms(10)
postgres.pro.cache 101ms(10)
postgres.pro.repeat 100ms(10)
sqlite.pro 117ms(10)
sqlite.pro.cache 137ms(10)
sqlite.pro.repeat 136ms(10)

Tree Cleanup - Remove All

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.
await redb.SyncSchemeAsync<DepartmentProps>();

var sw = Stopwatch.StartNew();

var existing = await redb.TreeQuery<DepartmentProps>().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();
TreeCleanupSoftDeleteAsyncPro
MS Pro 161ms(202)
mssql.pro.cache 129ms(202)
mssql.pro.repeat 181ms(202)
postgres.ef 87ms(202)
postgres.ef.repeat 87ms(202)
PG Pro 84ms(202)
postgres.pro.cache 66ms(202)
postgres.pro.repeat 72ms(202)
sqlite.pro 17ms(0)
sqlite.pro.cache 25ms(202)
sqlite.pro.repeat 22ms(202)

Tree Create BULK - Fast

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
await redb.SyncSchemeAsync<DepartmentProps>();
// 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<IRedbObject<DepartmentProps>>().ToList());

sw.Stop();

var rate = nodes.Count * 1000 / Math.Max(sw.ElapsedMilliseconds, 1);
GenerateTree
private static List<TreeRedbObject<DepartmentProps>> GenerateTree(long[] ids)
    {
        var nodes = new List<TreeRedbObject<DepartmentProps>>();
        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<long>();
        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;
    }
TreeBulkAddNewObjectsAsyncPro
MS Pro 206ms(101)
mssql.pro.cache 177ms(101)
mssql.pro.repeat 182ms(101)
postgres.ef 99ms(101)
postgres.ef.repeat 80ms(101)
PG Pro 76ms(101)
postgres.pro.cache 60ms(101)
postgres.pro.repeat 64ms(101)
sqlite.pro 62ms(101)
sqlite.pro.cache 201ms(101)
sqlite.pro.repeat 146ms(101)