Models: Getting Started
- Introduction
- Complete Example: Model Lifecycle
- Defining Models
- Retrieving Models
- Retrieving Single Models
- Inserting and Updating Models
- Deleting Models
- Query Scopes
- Events
- Not Yet Available
Introduction
DotBlaze models are an Eloquent-style active record on top of EF Core. Each table has a model class; the class has static methods to query the table and instance methods to save, update, and delete rows:
var post = await Post.FindOrFail(1);
post.Title = "Hello again";
await post.Save();Models get their DbContext from the active service scope (an HTTP request, a job, a command), so there is nothing to inject. See Where the Database Can Be Used.
Defining Models
A model extends Model<T>, where T is the class itself. Models live in app/Models by convention; any Model<T> class in the application assembly is found automatically:
namespace App.Models;
public class Post : Model<Post>
{
public long Id { get; set; }
public long UserId { get; set; }
[Fillable] public string Title { get; set; } = "";
[Fillable] public string Body { get; set; } = "";
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
public User? User { get; set; }
[Appends] public string Excerpt => Str.Limit(Body, 120);
public static Query<Post> Latest(Query<Post> q) => q.OrderByDesc(p => p.Id);
}Columns are public properties with a getter and setter. Unlike Eloquent, every column is declared, which gives you type checking and IntelliSense. The table itself is created by a migration.
Model Conventions
Table Names
The table name is the class name in plural snake_case: Post → posts, BlogCategory → blog_categories. Pluralization follows simple English rules (no irregular words such as person → people). Use the standard [Table] attribute for anything else:
using System.ComponentModel.DataAnnotations.Schema;
[Table("people")]
public class Person : Model<Person>
{
// ...
}Column Names
Property names are mapped to snake_case columns: UserId → user_id, CreatedAt → created_at. Override a single column with [Column]:
[Column("mail")] public string Email { get; set; } = "";Get-only properties (such as Excerpt above) are not columns.
Primary Keys
The primary key is normally a property named Id. Use long Id with t.Id() in the migration (a bigint auto-increment column), or int Id with t.Increments("id"). The key is set after the model is first saved.
String and GUID keys work too. A new instance is inserted even when its key is already assigned; Exists records whether the instance was loaded or saved. For application-assigned keys, use a non-generated column and [DatabaseGenerated(DatabaseGeneratedOption.None)]:
public class Document : Model<Document>
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; } = Str.Ulid();
[Fillable] public string Title { get; set; } = "";
}Import System.ComponentModel.DataAnnotations.Schema; create id as a string column with a primary key in the migration. A database identity column still follows that database's rules for explicit values.
Timestamps
If the model has a DateTime or DateTime? property named CreatedAt and/or UpdatedAt, DotBlaze fills them on save, in UTC: CreatedAt when the row is inserted (unless you already set it), UpdatedAt on every save that changes something. The migration's t.Timestamps() creates both columns. Models without these properties simply have no timestamps.
Database Connections
Models use the default connection from config/Database.cs. Use [Connection] to put a model on another connection:
[Connection("pgsql")]
public class Flight : Model<Flight>
{
// ...
}Relationships across connections are not supported.
Retrieving Models
All returns every row:
foreach (var post in await Post.All())
{
Console.WriteLine(post.Title);
}Building Queries
Static methods such as Where, OrderBy, and With start a Query<T>. Conditions are C# lambdas that EF Core translates to SQL:
var books = await Book.Where(b => b.Price < 20)
.OrderBy(b => b.Title)
.Take(10)
.Get();Query() starts an empty query. These methods build a query:
| Method | Description |
|---|---|
Where(b => ...) | Add a condition. Several calls are joined with AND. Use || inside the lambda for OR. |
OrderBy(b => b.Col) / OrderByDesc(b => b.Col) | Sort. |
Skip(n) / Take(n) | Offset and limit. |
With(b => b.Author) / With("Posts.Comments") | Eager load relationships, see Eager Loading. |
Scope(Post.Latest) | Apply a query scope. |
AsNoTracking() | Read without change tracking. |
WithTrashed() / OnlyTrashed() | Include or select soft deleted rows. |
These methods run it:
| Method | Returns |
|---|---|
Get() | Collection<T> of all matches. |
First() | The first match, or null. |
FirstOrFail() | The first match, or throws ModelNotFoundException. |
Find(id) / FindOrFail(id) | The row with that primary key. |
Count() | int number of matches. |
Exists() | true if there is at least one match. |
Pluck(b => b.Title) | Collection of a single column or expression. |
Paginate(perPage, page) | A Paginator<T>. |
var count = await Book.Query().Count();
var prices = await Book.OrderBy(b => b.Price).Take(2).Pluck(b => b.Price);
var exists = await User.Where(u => u.Email == "test@example.com").Exists();For anything Query<T> does not wrap, AsQueryable() returns the underlying EF Core IQueryable<T>, with every LINQ and EF Core operator available:
var totals = await Book.Query().AsQueryable()
.GroupBy(b => b.AuthorId)
.Select(g => new { AuthorId = g.Key, Total = g.Sum(b => b.Price) })
.ToListAsync();Collections
All and Get return a Collection<T>, DotBlaze's Laravel-style collection. It is enumerable, so foreach and LINQ work, and it adds helpers such as Pluck, KeyBy, and IsEmpty:
var names = (await Author.Scope(Author.Active).Get()).Pluck(a => a.Name);Tracking and Large Queries
By default, retrieved models are tracked by the scope's DbContext, which is what lets Save detect what changed. For large read-only queries, AsNoTracking() is faster and uses less memory:
var report = await Order.Query().AsNoTracking().Where(o => o.Total > 1000).Get();Calling Save on a model retrieved with AsNoTracking() still works. Its original values are retained, so only changed columns are updated.
Model queries also support bounded batches and streaming:
await Post.Query().Chunk(200, async posts =>
{
foreach (var post in posts) await Process(post);
return true; // false stops iteration
});
await Post.Where(p => !p.Published).ChunkById(200, async posts =>
{
foreach (var post in posts) await post.Update(new { Published = true });
return true;
});
await foreach (var post in Post.OrderBy(p => p.Id).Lazy(200)) { /* page at a time */ }
await foreach (var post in Post.OrderBy(p => p.Id).Cursor()) { /* read-only stream */ }Chunk and Lazy use the primary key order unless an order was supplied. Use ChunkById when changing or deleting matching rows; its key must have an ordered scalar type, such as an integer or string. Batches are read without tracking; successfully saved batch roots are detached afterwards. Cursor keeps a reader open: use batches for writes on the same connection.
Retrieving Single Models
var post = await Post.Find(1); // Post? (null when missing)
var post = await Post.Where(p => p.Title == "Hello").First(); // Post? (null when missing)Find accepts any value that converts to the key type, so Post.Find("1") works too.
Finding or Creating Models
var draft = await Post.FirstOrNew(new { Slug = "hello" }, new { Title = "Hello" });
var post = await Post.FirstOrCreate(new { Slug = "hello" }, new { Title = "Hello" });
var updated = await Post.UpdateOrCreate(new { Slug = "hello" }, new { Title = "Revised" });The first object identifies a row; the second supplies creation values (or updates for UpdateOrCreate). FirstOrNew returns an unsaved instance when no row matches. All three honor global scopes and mass-assignment rules, and are also available on Query<T>. Put a unique index on the identifying columns. FirstOrCreate recovers from a competing insert only if the matching row can then be found; other write failures propagate.
Exists is true after retrieval or a successful insert. WasRecentlyCreated identifies an instance inserted during its lifetime. Replicate(except...) creates an unsaved copy of scalar attributes, excluding primary keys, creation/update timestamps, and the named exceptions:
var copy = post.Replicate("Slug");
copy.Slug = "hello-copy";
await copy.Save();Not Found Exceptions
FindOrFail and FirstOrFail throw a ModelNotFoundException instead of returning null. If it is not caught during an HTTP request, DotBlaze turns it into a 404 response (see Error Handling):
var post = await Post.FindOrFail(id);Route Model Binding
A controller action parameter whose type is a model is loaded with FindOrFail using the route parameter of the same name, so a missing row gives a 404:
// Route.Resource<PostController>("/posts", parameter: "post");
public async Task<IActionResult> Show(Post post)
{
await post.Load(p => p.User);
return View(post);
}Inserting and Updating Models
Inserts
Create an instance, set its properties, and call Save:
var book = new Book { AuthorId = author.Id, Title = "DotBlaze in Action", Price = 30 };
await book.Save();
book.Id; // set by the databaseCreate fills a new model from an anonymous object through mass assignment, saves it, and returns it:
var user = await User.Create(new { Name = "Ali", Email = "ali@example.com", Password = "secret" });Updates
Change a retrieved model and call Save. Only changed columns are written. An unchanged model still fires Saving and Saved, but no update query or Updating/Updated events:
var post = await Post.FindOrFail(1);
post.Title = "Updated title";
await post.Save();Update mass-assigns the given attributes and saves:
await post.Update(new { request.Title, request.Body });Refresh reloads the model's columns from the database:
await post.Refresh();
var separate = await post.Fresh(); // a separate, untracked instance, or null if the row is goneNOTE
Models in a scope share a DbContext, but Save writes only the target model, new models reachable through its navigation graph, and its pivot changes. Each new related model gets its own casts, events, and timestamps. Pending edits on other existing models stay in memory and remain dirty, including after a failed save. Hard deletes are database deletes; cascading follows the foreign keys defined in your migrations.
Upgrading from scope-wide saves: call Save on each model you intend to persist. New instances with assigned keys now insert; use Find/FindOrFail to update an existing record. No database conversion is required. Deploy application code that depends on these semantics together with the framework; rolling back the framework restores scope-wide saves and key-based insert/update inference. For an explicit EF unit of work, DB.Connection().Context.SaveChangesAsync() remains available, using EF's own behavior rather than model events and set-casts.
SaveQuietly() performs a normal save, including casts and timestamps, without model events. To suppress model events for several operations in the current asynchronous flow:
await Model.WithoutEvents(async () =>
{
await post.Save();
await another.Delete();
});Exceptions restore event delivery. Ordinary application events are unaffected.
Examining Attribute Changes
IsDirty tells you whether a tracked model has unsaved changes, optionally for one property (use the C# property name). GetDirty returns the changed properties and their new values:
var author = await Author.FindOrFail(1);
author.Name = "Ali Updated";
author.IsDirty(); // true
author.IsDirty(nameof(Author.Name)); // true
author.IsDirty(nameof(Author.Password)); // false
author.GetDirty(); // { "Name": "Ali Updated" }
await author.Save();
author.IsDirty(); // falseGetKey() returns the primary key value.
IsClean(property?) is the inverse of IsDirty. GetOriginal() returns the original attribute snapshot; GetOriginal("Title") reads one value. GetChanges() and WasChanged(property?) describe the last write, including timestamps. A no-op save leaves that last-write history intact. Original values and dirty detection also work on untracked instances.
Mass Assignment
Create, Update, and Fill set properties from an anonymous object or a dictionary. To keep request data from setting columns it should not (an IsAdmin flag, a foreign key), only allowed properties are assigned.
Mark the allowed properties with [Fillable]:
public class Author : Model<Author>
{
public long Id { get; set; }
[Fillable] public string Name { get; set; } = "";
public bool IsActive { get; set; } = true;
}
var author = await Author.Create(new { Name = "Ali", IsActive = false });
author.IsActive; // true: IsActive is not fillable, so it was ignoredOr mark the forbidden ones with [Guarded]; every other settable property except Id is then fillable:
public class Tag : Model<Tag>
{
public long Id { get; set; }
[Guarded] public string Secret { get; set; } = "";
public string Name { get; set; } = "";
}The rules:
- If any property has
[Fillable], only those properties are fillable ([Guarded]is then ignored). - Keys that are not fillable, or do not exist on the model, are silently ignored.
- Keys are matched ignoring case and underscores, so
name,Name, andNAMEall setName, anduser_idsetsUserId. - A model with neither
[Fillable]nor[Guarded]is totally guarded:Create,Update, andFillthrow aMassAssignmentException. Set its properties directly instead.
Fill assigns without saving and returns the model:
var post = new Post { UserId = userId }.Fill(new { request.Title, request.Body });
await post.Save();Mass Updates
Update, Increment, Decrement, and Delete on a model query change every matching row in one statement:
await Post.Where(p => p.UserId == user.Id).Update(new { Published = true });
await Post.Where(p => p.Id == id).Increment(p => p.Views);
await Post.Where(p => p.Id == id).Decrement(p => p.Stock, 2);
await Post.Where(p => p.CreatedAt < cutoff).Delete(); // soft delete for ISoftDeletes models
await Post.WithTrashed().Where(...).ForceDelete(); // really delete
await Post.OnlyTrashed().Where(...).Restore();Like Laravel, these run in the database without loading the models: no model events, no mass-assignment rules, and no casts that run on save (such as Hashed). UpdatedAt is set when the model has it. Each returns the number of affected rows. Models of that type already loaded in the scope (without unsaved changes) are forgotten, so the next query reads the new values.
For atomic inserts-or-updates use the model query's Upsert:
await Product.Query().Upsert(
new[] { new { Sku = "A", Name = "Alpha" }, new { Sku = "B", Name = "Beta" } },
uniqueBy: ["Sku"], update: ["Name"]);Names are model properties; column names and EF value converters are applied automatically. Timestamps are added, and an existing CreatedAt is not overwritten by the default update list. This is a database operation: it ignores query predicates/global scopes, model events, mass-assignment rules, and set-casts such as Hashed. The conflict columns need a database unique index.
On SQL Server, omit identity-generated columns such as Id from the input and match on a unique non-identity key. The MERGE statement includes an insert branch even when the row already exists, so explicit identity values require IDENTITY_INSERT. To update an existing row by its identity key, use Where(...).Update(...).
Deleting Models
var post = await Post.FindOrFail(1);
await post.Delete();Soft Deleting
A model that implements ISoftDeletes is not removed by Delete; its DeletedAt is set instead, and normal queries skip it. Add the column with t.SoftDeletes() in the migration:
public class Book : Model<Book>, ISoftDeletes
{
public long Id { get; set; }
// ...
public DateTime? DeletedAt { get; set; }
}await book.Delete();
book.Trashed(); // true
await Book.Find(book.Id); // null
await book.Restore(); // DeletedAt = null again
await book.ForceDelete(); // really removes the rowForceDelete also works on models without soft deletes. Restore on a model without ISoftDeletes throws.
Querying Soft Deleted Models
var all = await Book.WithTrashed().Get(); // live and trashed
var trashed = await Book.OnlyTrashed().Get(); // trashed only
var book = await Book.WithTrashed().Find(id);Query Scopes
A local scope is a static method that takes a Query<T> and returns one. Apply it with Scope, either first or in the middle of a query:
public class Author : Model<Author>
{
// ...
public static Query<Author> Active(Query<Author> q) => q.Where(a => a.IsActive);
}
var active = await Author.Scope(Author.Active).Get();
var posts = await Post.Scope(Post.Latest).With(p => p.User).Paginate(10);Scopes with parameters can be lambdas:
public static Func<Query<Post>, Query<Post>> By(long userId) => q => q.Where(p => p.UserId == userId);
var mine = await Post.Scope(Post.By(userId)).Get();Global Scopes
Register named predicates in a provider's Boot, before using a database context:
Post.AddGlobalScope("published", p => p.Published);These are EF named query filters, so they apply to root queries, mapped navigation loading, relationship subqueries, and aggregate queries. A predicate can reference a current-scope value through an expression, for example p => p.TenantId == CurrentTenant.Id; do not capture one request's tenant ID in a local variable during application boot.
await Post.WithoutGlobalScope("published").Get();
await Post.WithoutGlobalScopes().Get(); // removes this model's filters, including soft deletesWithTrashed and OnlyTrashed remove only this model's reserved SoftDeletes filter; custom scopes and related models' filters remain in force. Scope removals can be chained and are isolated by model, even when two models use the same scope name. Registering a scope after a context has been obtained in the same service scope is refused. Required EF navigations can use inner joins, so a related model's filter may also remove the root row from an eager-loaded result.
Events
Saving and deleting a model dispatches these events through the Event facade, each carrying the model in its Model property:
| Event | When |
|---|---|
Saving<T> | Before every insert or update. |
Creating<T> / Created<T> | Before / after an insert. |
Updating<T> / Updated<T> | Before / after an update. |
Saved<T> | After every insert or update. |
Deleting<T> / Deleted<T> | Before / after Delete or ForceDelete. |
Restoring<T> / Restored<T> | Before / after Restore of a soft-deleted model. |
Trashed<T> | After the soft-delete columns are written. |
ForceDeleting<T> / ForceDeleted<T> | Before / after a permanent delete. |
The order for an insert is Saving, Creating, (insert), Created, Saved. An unchanged save fires Saving, Saved. A soft delete fires Deleting, Trashed, Deleted and writes only the deletion/update timestamps, retaining other pending edits. A force delete fires ForceDeleting, Deleting, Deleted, ForceDeleted.
Handle them with a listener class, which DotBlaze discovers automatically:
public class StampSlug : Listener<Saving<Post>>
{
public override Task Handle(Saving<Post> e)
{
e.Model.Slug = Str.Slug(e.Model.Title);
return Task.CompletedTask;
}
}Changes made in Saving or Creating/Updating listeners are saved with the model. See Events for closure listeners and queued listeners. Because model events go through the Event facade, Event.Fake() records them in tests (and observers do not run).
Every model event also implements IModelEvent (with Kind, ModelType, and Model), so one listener can handle all of them, and a wildcard listener can match their Laravel-style names such as eloquent.created: SampleApp.Models.Post.
Observers
An observer groups a model's event handlers in one class. Name each method after the event, taking the model:
public class PostObserver(ILogger<PostObserver> logger)
{
public void Creating(Post post) => post.Slug = Str.Slug(post.Title);
public async Task Deleted(Post post)
{
await Storage.Delete(post.CoverPath!);
logger.LogInformation("Post {Id} deleted", post.Id);
}
}Methods may be void or return Task; any model event name in the table above can be present. Register the observer with an attribute on the model, or in a provider's Boot method:
[ObservedBy(typeof(PostObserver))]
public class Post : Model<Post> { ... }
Post.Observe<PostObserver>();An observer is created for each event with services from DI. To stop a save or delete, throw an exception.
Not Yet Available
- Lazy loading does not exist, by design. Load relationships with
WithorLoad, see Relationships.
Complete Example: Model Lifecycle
The complete walkthrough provides a Post model, matching table, and author model. This test adds a persistence and mass-assignment check:
// Blog.Tests/ModelLifecycleTest.cs
using Blog.Models;
using DotBlaze.Testing;
using Xunit;
namespace Blog.Tests;
public class ModelLifecycleTest
{
[Fact]
public async Task Only_fillable_fields_change_and_saves_persist()
{
using var app = new TestApp<Program>();
await app.RefreshDatabase();
var user = await app.Run(() => User.Factory().Create());
var post = await app.Run(async () =>
{
var value = new Post { UserId = user.Id };
await value.Update(new { Title = "Original", Body = "Body", UserId = -1L });
Assert.Equal(user.Id, value.UserId);
Assert.True(value.Exists);
Assert.NotNull(value.CreatedAt);
return value;
});
await app.Run(() => post.Update(new { Title = "Revised" }));
await app.AssertDatabaseHas("posts", new { id = post.Id, title = "Revised", user_id = user.Id });
}
}Run dotnet test Blog.Tests --filter FullyQualifiedName~ModelLifecycleTest using the sibling test project. The attempted UserId mass assignment is ignored because the model only marks title and body fillable. Direct property assignment remains trusted application code; it is not governed by the fillable allowlist.