Code Examples

Data Model - EmployeeProps Click to view data model used in all examples
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; }
}

Unique Keys - [RedbUnique] and value_unique

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

// 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<ProductProps>
{
    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<ProductProps>
    {
        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<ProductProps>(p => p.Sku, sku);

// 4. NULL keys do not collide: both keyless products save fine.
await redb.SaveAsync(new RedbObject<ProductProps> { name = "no-key-a", Props = new ProductProps { Title = "Draft A" } });
await redb.SaveAsync(new RedbObject<ProductProps> { 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<ProductProps>
{
    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<ProductProps>
{
    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<ProductProps>
    {
        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();
UniqueRedbUniqueValueUniqueGetByUniqueAsyncSoftDeleteIRedbService.GetByUniqueAsyncIRedbService.SaveAsync
PG Pro 692ms(5)
postgres.pro.repeat 651ms(5)
postgres.pro.cache 643ms(5)
MS Pro 506ms(5)
mssql.pro.repeat 605ms(5)
mssql.pro.cache 420ms(5)
sqlite.pro 37ms(5)
sqlite.pro.repeat 18ms(5)
sqlite.pro.cache 13ms(5)