The Attachments module contains 2 main components:
Every EntityAttachment links to the same Attachment entity, whichever entity owns it:
flowchart LR
product["Product"] -- "Attachments<br/>(ObjectId)" --> pa["ProductAttachment<br/>ObjectType = Product"]
article["Article"] -- "Attachments<br/>(ObjectId)" --> aa["ArticleAttachment<br/>ObjectType = Article"]
pa -- AttachmentId --> att[("Attachment<br/>one table for every owner")]
aa -- AttachmentId --> att
att -- file content --> afs["AttachmentFileService"]
afs --> fs["IFileService<br/>file system · Azure Blob · SFTP"]
All attachments for all entities are stored in one table.
public interface IAttachment : IBinaryFile, IHasTimestamps;
public interface IAttachment<TKey> : IAttachment, IEntity<TKey>;
The Attachment is based on IBinaryFile (Part of Regira.IO module):
string? FileName - The name of a file (not full path)string? Identifier - Identifier in a specific context (Prefix + Filename)string? Prefix - The folder structure, except the root folderstring? Path - Where the file is stored, relative to the file service’s root: AttachmentFileService stores the identifier, never the absolute path, so the root can movestring? ContentType - MIME type of the filelong Length - Size of the file in bytesbyte[]? Bytes - Content as a byte arrayStream? Stream - Content as a streamThe AttachmentFileService handles the physical file storage and retrieval for attachments.
public class AttachmentFileService<TAttachment, TKey>(IFileService fileService) : IAttachmentFileService<TAttachment, TKey>
{
public async Task<byte[]?> GetBytes(TAttachment item, CancellationToken token = default)
public async Task SaveFile(TAttachment item, CancellationToken token = default)
public async Task RemoveFile(TAttachment item, CancellationToken token = default)
public string GetIdentifier(string fileName)
public string GetRelativeFolder(TAttachment item)
}
It uses an underlying IFileService to perform the actual file operations.
Useful IFileService implementations:
BinaryFileService: Local File SystemBinaryBlobService: Azure Blob StorageSftpService: SFTP/SSH// (simplified)
public interface IEntityAttachment<TKey, TObjectKey> : IEntityAttachment<TKey, TObjectKey, int, Attachment>;
public interface IEntityAttachment<TKey, TObjectKey, TAttachmentKey> : IEntityAttachment<TKey, TObjectKey, TAttachmentKey, Attachment<TAttachmentKey>>;
public interface IEntityAttachment<TKey, TObjectKey, TAttachmentKey, TAttachment> : IEntity<TKey>, IHasObjectId<TObjectKey>, IEntityAttachment, ISortable
where TAttachment : class, IAttachment<TAttachmentKey>, new()
{
string? ObjectType { get; } // Name of owning entity type (e.g. Product, Article, ...)
// a new link's file (when it carries no Attachment), or a kept link's new name / replacement bytes
string? NewFileName { get; set; }
[Obsolete] string? NewContentType { get; set; } // ignored: the content type follows the file name
byte[]? NewBytes { get; set; }
TAttachmentKey AttachmentId { get; set; }
new TAttachment? Attachment { get; set; }
}
Inherit the EntityAttachment base (which maps to EntityAttachment<int, int, int, Attachment>) and
set ObjectType in the constructor.
public class ProductAttachment : EntityAttachment
{
public ProductAttachment() => ObjectType = nameof(Product);
}
Each owning entity gets its own subclass: the class is the join table and its constructor pins one
ObjectType, so attaching files to a second entity means a second subclass, DbSet, controller (none when its
endpoints are mapped) and registration.
After defining the model of the EntityAttachment, 2 interfaces have to be implemented on the Owning Entity:
IHasAttachmentsIHasAttachments<TEntityAttachment>// other properties and interfaces are omitted
public class OwningEntity: IHasAttachments, IHasAttachments<MyEntityAttachment>
{
// ...
// Add these 3 properties
// HasAttachment is yours to fill: nothing populates it, so it serializes as null even for a row that
// has attachments. Filtering on it is also yours to wire — Regira.Entities.EFcore ships the
// FilterHasAttachment(bool?) query extension, but no query builder calls it for you. It is a flag, not a
// column, hence [NotMapped] (System.ComponentModel.DataAnnotations.Schema).
[NotMapped]
public bool? HasAttachment { get; set; }
public ICollection<MyEntityAttachment>? Attachments { get; set; }
// implicit interface implementation
ICollection<IEntityAttachment>? IHasAttachments.Attachments
{
get => Attachments?.Cast<IEntityAttachment>().ToArray();
set => Attachments = value?.Cast<MyEntityAttachment>().ToArray();
}
}
// Add a DbSet for each EntityAttachment type
public DbSet<MyEntityAttachment> MyEntityAttachments { get; set; } = null!;
// Update OnModelCreating
modelBuilder.Entity<OwningEntity>(entity =>
{
entity.HasMany(e => e.Attachments)
.WithOne()
.HasForeignKey(e => e.ObjectId)
.HasPrincipalKey(e => e.Id);
});
The owner-side mapping is required. ObjectId is not a conventional foreign-key name and the link has no
navigation back to its owner, so without it EF adds a shadow key of its own: link rows are saved without an
owner, the owner’s Attachments loads empty and ?hasAttachment=true matches nothing. Startup validation warns.
Mark the link entity — a flag, or its SortOrder, which is assigned from the incoming array position. A foreign
key from the owner to one of its own attachments makes the two tables reference each other; see
Entity Models: Referencing one of your own children.
An application that maps its entities with MapEntityEndpoints() writes no attachment controller: the routes below
are mapped under the owner’s route, for the int-keyed link (IHasAttachments<TLink>), and send the same requests
(Web Endpoints → Mapped Endpoints). An owner with another key type keeps a
controller.
The custom EntityAttachmentController must derive from EntityAttachmentControllerBase. Set the class
[Route] to the owner base path — the base actions append the sub-routes
({objectId}/attachments, attachments/{id}, {objectId}/files, files/{id}, …).
// using default DTOs (EntityAttachmentDto & EntityAttachmentInputDto))
[ApiController, Route("products")]
public class ProductAttachmentsController : EntityAttachmentControllerBase<ProductAttachment>;
// or using custom DTOs
[ApiController, Route("products")]
public class ProductAttachmentsController : EntityAttachmentControllerBase<ProductAttachment, MyAttachmentDto, MyAttachmentInputDto>;
Endpoints exposed (with [Route("products")]):
| Method | Route | Purpose |
|---|---|---|
POST |
{objectId}/files |
Upload a file (multipart IFormFile + input model) |
PUT |
{objectId}/files/{id} |
Replace an existing file |
GET |
{objectId}/attachments |
List attachments for an owner |
GET |
attachments |
List links across owners (EntityAttachmentSearchObject) |
GET |
attachments/{id} |
Attachment metadata |
PUT |
{objectId}/attachments/{id} |
Update attachment metadata: NewFileName renames the file and retypes it, NewBytes replaces its content; the link keeps its attachment, whatever AttachmentId the body sends |
DELETE |
attachments/{id} |
Remove the link, and its attachment and file unless another link of its type names it |
GET |
files/{id} · {objectId}/files/{fileName} |
Download the file |
Every {id} is the id of the link row (EntityAttachmentDto.Id), not its AttachmentId; {objectId} is the
owner’s id. The two PUT routes answer 400 for a link of another owner, a ValidationProblemDetails keyed
objectId.
An attachment’s content type follows its file name — whatever the client declared, and whoever writes the row — and
a download is served with X-Content-Type-Options: nosniff and, for every file but a PDF,
Content-Security-Policy: sandbox, so a file renders but runs no script on the API’s origin. A write a
validator refuses answers 400 with a ValidationProblemDetails
(Input Exceptions).
Validators scoped to the link entity run for these endpoints only. A POST or PUT of the owner whose input carries
Attachments syncs the links itself — it adds one for each new entry with NewBytes, and on a PUT renames and
replaces a kept link’s file from its NewFileName and NewBytes and deletes the ones the array leaves out — and runs
only the owner’s validators. A kept link keeps its attachment, whatever AttachmentId the entry sends, and a new one may point
only at an attachment the owner already links: one naming another owner’s is cleared, and without NewBytes of its
own the save answers 409. The
upload route always creates a link, whatever Id its form sends.
Scope an upload yourself. An upload is a create: it takes the owner’s id from the route and runs no query, so a
global filter (tenant, owner) never sees it, and any authenticated caller can attach a file to a row it cannot read.
Scope the link, too. The owner’s global filter never runs on the link entity, which has no owner column and no
navigation back to the owner. So on an owner scoped per user or tenant, every other attachment route — the list,
details, both downloads, the link’s PUT and DELETE — reads across owners until a global filter on the link entity
reruns the owner’s scope through the owner’s DbSet (Owners.Any(o => o.Id == link.ObjectId && …)). With it those
routes answer 404 for another owner’s file; the upload still runs no query. Add a validator on the link entity that
re-runs the owner’s scope on Add and refuses when it resolves nothing — a 400, where the read path answers 404 — or
override the controller’s Add to answer 404. Read scope is not write scope either: a read scope widened on purpose,
a manager seeing their reports’ rows, grants writes and deletes on those rows too, so put a narrower ownership check in
a validator, which runs on a delete as well. Repeat a link rule, such as the allowed file types or a file that
must not be deleted, in the owner’s validator, or keep Attachments off the owner’s input DTO.
Attachments need two registrations:
WithAttachments(factory) registers the shared Attachment entity, the file store, the
bytes→file primer, and AttachmentFileReactor, which removes a file that new bytes replaced, and a deleted
attachment’s file, after the commit (see Files and transactions below).HasAttachments<…>(x => x.Attachments) — chained on the owner’s For<>() builder — registers the
typed per-owner read/write services, the link prepper and DTO mapping.Call WithAttachments once per attachment type. A second call for the same type, from another DbContext’s
UseEntities, replaces the first one’s file store and adds a second file reactor, which reads the other database and
so never finds the row it checks.
The bytes Details loads are the attachment’s stored file, not new content: saving a rename or another metadata edit
leaves the file where it is. Bytes or a stream set in their place replace it, stored under the file name’s extension.
Files and transactions. A replaced or deleted attachment’s file is removed after the commit, by
AttachmentFileReactor, once the attachment’s own row no longer names it. A save that fails, a rollback — to a
savepoint too — and a context without the reactor wiring leave a file no row names; an application that needs a clean
store sweeps it against the stored Path values:
AttachmentFileReactor reads the attachment’s row by key, past query filters, and removes the
replaced or deleted file only when the row no longer names it: a save an interceptor suppressed, or one a rollback to
a savepoint undid, changed no row, and the file stays. Only that row is read: two attachment rows naming one path —
one added with another’s Path and no content of its own — share the file, and deleting either removes it.HasAttachments<…>(x => x.Attachments, a => a.HasStrictRelation = false) keeps the attachments the owner’s links
leave on the owner’s save, for attachments that outlive their links; the link’s own DELETE and a file replace
still delete an attachment no other link names.RemoveItem on the owner’s write service — it runs once the validators passed — call the base
first, and, unless the owner is IArchivable (a soft delete keeps them for a restore), remove its links and each
attachment no other link of that owner type names, checking past query filters and removing through
RemoveGuarded, as the library removes a link’s attachment. They go in the owner’s own save, and
AttachmentFileReactor removes the files after the commit. Not in a reactor: it runs after the commit, when the
links are gone. Sweeping every Attachment row no link names instead also takes the ones
HasStrictRelation = false keeps. An attachment linked from several owner types needs each link type checked.DbContextWiring.Reactors, part of UseDefaults()), no file is removed; the startup
validation warns about such a context.using Regira.Entities.DependencyInjection.Attachments; // HasAttachments
using Regira.Entities.DependencyInjection.Extensions; // UseEntities, UseDefaults
using Regira.Entities.Web.Attachments.DependencyInjection; // UseAttachmentUris
using Regira.IO.Storage.FileSystem; // BinaryFileService, FileSystemOptions
builder.Services
.AddHttpContextAccessor() // required for attachment Uri resolution
.UseEntities<MyDbContext>(o =>
{
o.UseDefaults();
o.UseAttachmentUris(); // web apps: resolve attachment DTO Uri's (ASP.NET Core)
/* ... */
})
// 1. shared Attachment entity + file store + bytes→file primer + AttachmentFileReactor
.WithAttachments(_ => new BinaryFileService(
new FileSystemOptions
{
RootFolder = ApiConfiguration.AttachmentsDirectory
}
))
// 2. typed per-owner services + link prepper + DTO mapping
.For<Product>(e => e.HasAttachments<MyDbContext, Product, ProductAttachment>(x => x.Attachments));
Owner with its own input DTO? Declare the collection on the owner’s input DTO —
public ICollection<EntityAttachmentInputDto>? Attachments { get; set; }— and mirror it on the read DTO withICollection<EntityAttachmentDto>?. Without the input property, the convention map yields anullcollection on every parent save, which the sync reads as “attachments not sent”: adds, removes and reorders through the parent are silently ignored while the/{objectId}/attachmentssub-routes keep working. Startup validation warns about this shape.
File-service factory.
WithAttachmentstakes anIFileServicefactory (Func<IServiceProvider, IFileService>), not a registeredIFileService— so your app can still register its own store(s) elsewhere. Build one inline (WithAttachments(_ => new BinaryFileService(...))) or reuse an app-registered one (WithAttachments(p => p.GetRequiredService<IFileService>())). It’s wrapped into the registeredIAttachmentFileService<Attachment, int>— one per attachment base type, so each can use a different store.
Reading file bytes. Use the built-in download endpoints, or inject
IAttachmentFileService<Attachment, int>and callGetBytes(item). Consuming code references files byIdentifier(the public storage key, populated when you load through the entity service);Pathis internal and isn’t mapped to DTOs — clients get a downloadUriinstead.
Ordering. Attachment order travels by array position:
HasAttachmentswiresSetSortOrder()over the incoming collection, so every parent save assignsSortOrder = index— the input DTO carries no sort field on purpose, and any client-sent value is overwritten. The read DTO exposesSortOrder; order the eager-load (x.Attachments!.OrderBy(a => a.SortOrder)) so a round-trip is stable.
o.UseAttachmentUris()(web apps). Populates the attachment DTOUri.Entities.DependencyInjectiondoesn’t referenceEntities.Web, so the ASP.NET Core resolver (LinkGenerator+IHttpContextAccessor) is opt-in (namespaceRegira.Entities.Web.Attachments.DependencyInjection). Call it in theUseEntitiesoptions block, before entities are registered; without it,Uriisnull. TheUrilinks to the owner’s mapped download whenMapEntityEndpoints()serves it (the first mapping, for an owner mapped twice), else to theGetFileaction on the attachment entity’s controller ({EntityAttachment}Controller : EntityAttachmentControllerBase<…>), so one of the two must be in place. If you replace the generated attachment endpoints with a custom download route, the link generator finds no match andUristaysnull— use the download endpoint directly. It is alsonulloutside an active request (e.g. during seeding).
Every attachment route sends a request through IEntitySender, from an attachment controller and from the mapped
routes alike (Web Endpoints → Entity Operations). A closed handler for that
request changes the route on both, and for a job that sends the same request. TLink is the link entity:
| Route | Request | Default handler |
|---|---|---|
POST {objectId}/files |
UploadAttachmentCommand<TLink, TDto, TInputDto> |
UploadAttachmentHandler<,,> |
PUT {objectId}/attachments/{id} |
UpdateAttachmentCommand<TLink, TDto, TInputDto> |
UpdateAttachmentHandler<,,> |
PUT {objectId}/files/{id} |
ReplaceAttachmentFileCommand<TLink, TDto> |
ReplaceAttachmentFileHandler<,> |
GET files/{id}, GET {objectId}/files/{fileName} |
AttachmentFileQuery<TLink> |
AttachmentFileHandler<> |
GET attachments/{id}, both lists, DELETE attachments/{id} |
DetailsQuery, ListQuery, DeleteCommand of TLink |
the entity handlers |
The requests live in Regira.Entities.Mediator.Requests and the default handlers in
Regira.Entities.Mediator.Handlers. Deriving from the default handler keeps what it does. This one records every
download it serves:
using Regira.Entities.Attachments.Models;
using Regira.Entities.Mediator.Abstractions;
using Regira.Entities.Mediator.Handlers;
using Regira.Entities.Mediator.Requests;
// the owner implements IHasAttachments<ProductAttachment> and registers HasAttachments() (Owning Entity, above)
public class Product : IEntityWithSerial { public int Id { get; set; } public string? Title { get; set; } }
public class ProductAttachment : EntityAttachment
{
public ProductAttachment() => ObjectType = nameof(Product);
}
public class FileDownload
{
public int Id { get; set; }
public int LinkId { get; set; }
public DateTime DownloadedOn { get; set; }
}
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
public DbSet<FileDownload> FileDownloads => Set<FileDownload>();
}
// both downloads of a product's file, on an attachment controller or mapped, and a job's AttachmentFileQuery: the
// file as the default handler serves it, and a row for each download served
public class ProductFileHandler(IServiceProvider services, AppDbContext db) : AttachmentFileHandler<ProductAttachment>(services)
{
public override async Task<Attachment?> Handle(AttachmentFileQuery<ProductAttachment> request, CancellationToken token = default)
{
var file = await base.Handle(request, token);
if (file != null)
{
db.FileDownloads.Add(new FileDownload { LinkId = request.Id, DownloadedOn = DateTime.UtcNow });
await db.SaveChangesAsync(token);
}
return file;
}
}
public static class ProductFileOperations
{
public static IServiceCollection AddProductFileOperations(this IServiceCollection services)
=> services.AddTransient<IEntityRequestHandler<AttachmentFileQuery<ProductAttachment>, Attachment>, ProductFileHandler>();
}
AttachmentFileQuery — the one by name finds the link first — so one override covers them.
null answers 404.AttachmentFileQuery names only the link, so a download override
always matches. The other requests name the read DTO too, and the upload and the update the input DTO as well: an
attachment controller’s pair (EntityAttachmentControllerBase<ProductAttachment> sends EntityAttachmentDto and
EntityAttachmentInputDto), and on mapped routes the link’s UseMapping pair, else those two. No startup check
covers a handler for the link, so one for another pair is skipped without a word.