Skip to content

Models: Casts & Mutators ​

Introduction ​

Accessors, mutators, and casts transform values when you read them from or write them to a model. In DotBlaze, accessors and mutators are ordinary C# properties, and casts are declared with the [Cast] attribute.

EloquentDotBlaze
getFullNameAttribute / Attribute::getA get-only computed property
setNameAttribute / Attribute::setA property setter
'password' => 'hashed'[Cast(typeof(Hashed))]
'options' => AsArrayObject::class / 'json'[Cast(typeof(JsonCast<T>))]
Custom cast classAn EF Core ValueConverter, or an ISetCast

Accessors and Mutators ​

Defining an Accessor ​

An accessor is a get-only property computed from other properties. It is not a column:

csharp
public class Post : Model<Post>
{
    [Fillable] public string Body { get; set; } = "";

    public string Excerpt => Str.Limit(Body, 120);
}

Computed properties are left out of the model's JSON unless you mark them with [Appends], see Appending Values to JSON.

Defining a Mutator ​

A mutator is a property setter. C# 14's field keyword keeps it short:

csharp
public string Nickname { get; set => field = value.Trim(); } = "";

The setter runs whenever your code or mass assignment sets the property. Keep setters free of facades and I/O; for work that needs services, use a Saving<T> listener instead.

Attribute Casting ​

[Cast(typeof(...))] on a property takes one of two kinds of type:

  • an EF Core ValueConverter, which converts between the property and the column every time the model is written or read (for example JsonCast<T>), or
  • an ISetCast, which transforms the value once, just before the model is saved (for example Hashed).

Hashed Casting ​

Hashed hashes the value with the Hash facade before the model is saved:

csharp
public class User : Model<User>
{
    public long Id { get; set; }
    [Fillable] public string Email { get; set; } = "";
    [Fillable, Hidden, Cast(typeof(Hashed))] public string Password { get; set; } = "";
}

var user = await User.Create(new { Email = "ali@example.com", Password = "plain-password" });

Hash.Check("plain-password", user.Password); // true

A value that is already a hash is left alone, so saving the model again (or assigning an existing hash) never hashes twice. Empty strings are not hashed. Pair it with [Hidden] so the hash never shows up in JSON.

JSON Casting ​

JsonCast<T> stores an object as JSON in a text column (create it with t.Text(...) or t.Json(...)) and gives you a typed object on the model:

csharp
public class AuthorSettings
{
    public string Theme { get; set; } = "light";
}

public class Author : Model<Author>
{
    // ...
    [Fillable, Cast(typeof(JsonCast<AuthorSettings>))] public AuthorSettings Settings { get; set; } = new();
}

Changes inside the object are detected, so you can mutate it in place and save:

csharp
author.Settings.Theme = "dark";
await author.Save();

T can be any type System.Text.Json can serialize, such as List<string> or Dictionary<string, object>.

Value Converter Casts ​

Any EF Core ValueConverter whose constructor parameters are all optional can be used as a cast. DotBlaze creates it once and EF Core applies it in both directions, including in query parameters:

csharp
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

public enum Status { Draft, Published }

public sealed class StatusAsText() : ValueConverter<Status, string>(
    v => v.ToString(),
    s => Enum.Parse<Status>(s));

public class Post : Model<Post>
{
    // ...
    [Cast(typeof(StatusAsText))] public Status Status { get; set; }
}

EF Core's built-in converters work directly too, with no subclass needed:

csharp
[Cast(typeof(EnumToStringConverter<BookStatus>))] public BookStatus Status { get; set; }

Custom Set Casts ​

Implement ISetCast to transform a value before every save, like Hashed does. It needs a public parameterless constructor:

csharp
public sealed class Lowercase : ISetCast
{
    public object? Set(object? value) => (value as string)?.ToLowerInvariant();
}

public class User : Model<User>
{
    [Fillable, Cast(typeof(Lowercase))] public string Email { get; set; } = "";
}

Set casts run on every Save that writes something, after the Saving, Creating, and Updating events and before timestamps are set. They only change the value that is saved; there is no matching "get" step, so use a ValueConverter when you need both directions.

Complete Example: Hashed Cast Round-Trip ​

The template already supplies User.Password with Cast(typeof(Hashed)) and Hidden. In the Blog test project, create:

csharp
// Blog.Tests/PasswordCastTest.cs
using Blog.Models;
using DotBlaze;
using DotBlaze.Testing;
using Xunit;

namespace Blog.Tests;

public class PasswordCastTest
{
    [Fact]
    public async Task Saving_a_user_hashes_once()
    {
        using var app = new TestApp<Program>();
        await app.RefreshDatabase();
        await app.Run(async () =>
        {
            var user = await User.Create(new
            {
                Name = "Ada", Email = "cast@example.test", Password = "test-password",
            });
            var hash = user.Password;
            Assert.NotEqual("test-password", hash);
            Assert.True(Hash.Check("test-password", hash));
            user.Name = "Ada Updated";
            await user.Save();
            await user.Refresh();
            Assert.Equal(hash, user.Password);
        });
    }
}

Run dotnet test Blog.Tests --filter FullyQualifiedName~PasswordCastTest. Expected: one passing test. This proves that updating an unrelated field does not double-hash an existing password. Query-builder/bulk updates do not run this set-cast.