Custom data sources
Manage data that isn't in EF Core
StellarAdmin was created primarily with EF Core in mind, but nothing is preventing you from adding your own data sources. For example, you may want to use data from a REST API, use Dapper, or use your existing service or repository classes.
When using a custom data source, register your resource with AddResource<T>() (as opposed to AddEfCoreResource<T>()) and specify the data source by calling UseDataSource<TDataSource>() on the resource builder.
The example below registers a Supplier resource with a custom SupplierDataSource.
using StellarAdmin.Resources;
admin.AddResource<Supplier>(resource =>
{
// See the "Implementing the data source" section below for the source code of the SupplierDataSource
resource.UseDataSource<SupplierDataSource>();
// Specify the property to be used for the primary key so view, edit, and delete will work correctly
resource.UseKey(supplier => supplier.Code);
resource.Index(index =>
{
index.Columns(columns => columns.Add(supplier => supplier.Name, column => column.Sortable()));
index.EnableSearch();
index.EnablePaging();
});
resource.AllowCreate(create => create.Fields(fields => fields.Add(supplier => supplier.Name)));
resource.AllowEdit(edit => edit.Fields(fields => fields.Add(supplier => supplier.Name)));
resource.AllowDelete();
});When using a custom data source, StellarAdmin is unable to automatically detect the property that must be used as the primary key for the resource. Make sure to call UseKey() and set the property. If you don't do this, your edit and view pages, and delete action will not work, since those require a key value.
UseDataSource() automatically registers the data source as a scoped service, unless you've already registered it, so you can pass other services to its constructor.
Implementing the data source
Every data source must implement IResourceDataSource<T>, which lists the records for the index page. The data source must also implement the matching interfaces for the other pages you enable. For example, if you allow creating new resources, you must also implement the IResourceCreateHandler<T> interface.
| Interface | Methods | Used by |
|---|---|---|
IResourceDataSource<T> | ListAsync() | The index page |
IResourceCreateHandler<T> | CreateAsync() | The create page |
IResourceViewHandler<T> | FindAsync() | The view page |
IResourceEditHandler<T> | FindAsync() and UpdateAsync() | The edit and view pages |
IResourceDeleteHandler<T> | DeleteAsync() | Deleting |
The IResourceCrudDataSource<T> interface combines all of these interfaces, for a data source that supports every page. The example below implements IResourceCrudDataSource<Supplier> with an API client:
using StellarAdmin.Resources;
public class SupplierDataSource(SupplierApi api) : IResourceCrudDataSource<Supplier>
{
public async Task<ResourceListResult<Supplier>> ListAsync(
ResourceListRequest request, CancellationToken cancellationToken)
{
var suppliers = (await api.GetAllAsync(cancellationToken)).AsEnumerable();
if (request.Keys is { } keys)
suppliers = suppliers.Where(supplier => keys.Contains(supplier.Code));
if (request.Search is { } search)
suppliers = suppliers.Where(supplier =>
supplier.Name.Contains(search, StringComparison.OrdinalIgnoreCase));
if (request.Sort is { Field: nameof(Supplier.Name) } sort)
suppliers = sort.Direction == ResourceSortDirection.Ascending
? suppliers.OrderBy(supplier => supplier.Name).ThenBy(supplier => supplier.Code)
: suppliers.OrderByDescending(supplier => supplier.Name).ThenBy(supplier => supplier.Code);
var all = suppliers.ToList();
var page = request.Paging is { } paging
? all.Skip((paging.Page - 1) * paging.PageSize).Take(paging.PageSize).ToList()
: all;
return new ResourceListResult<Supplier>(page, all.Count);
}
public Task<Supplier?> FindAsync(string id, CancellationToken cancellationToken) =>
api.FindAsync(id, cancellationToken);
public async Task<ResourceOperationResult> CreateAsync(
Supplier model, CancellationToken cancellationToken)
{
await api.CreateAsync(model, cancellationToken);
return ResourceOperationResult.Success();
}
public async Task<ResourceOperationResult> UpdateAsync(
string id, Supplier model, CancellationToken cancellationToken)
{
if (await api.FindAsync(id, cancellationToken) is null)
return ResourceOperationResult.NotFound();
await api.UpdateAsync(id, model, cancellationToken);
return ResourceOperationResult.Success();
}
public async Task<ResourceOperationResult> DeleteAsync(string id, CancellationToken cancellationToken)
{
if (await api.HasOpenOrdersAsync(id, cancellationToken))
return ResourceOperationResult.ValidationFailed(null, "This supplier still has open orders.");
await api.DeleteAsync(id, cancellationToken);
return ResourceOperationResult.Success();
}
}You can use IResourceCrudDataSource<T> even if you did not enable all the pages and features for the resource. For example, if you did not enable deleting records, you can simply throw a NotImplementedException in the DeleteAsync() method since that method will never be called.
Filtering, sorting and pagination in ListAsync()
StellarAdmin passes the requested search, scope, sorting and pagination to the ListAsync() method via the request parameter. Your data source must apply these and return the records with filtering, sorting, and pagination applied.
The request parameter has the following properties.
| Property | Description |
|---|---|
Search | Contains the trimmed search text the user typed into the search box, or null if not specified. |
Scope | Specifies the id of the selected scope, or null. |
Sort | Specifies the Field by which the results must be sorted and Direction of the sort, or null. |
Paging | Specifies the Page, starting at 1, and the PageSize, or null to return all matching records. |
Keys | The keys of the specific records to return, or null. StellarAdmin sets it when inline editing reloads saved rows, and when a lookup loads the currently selected record(s). |
The ListAsync() method return a ResourceListResult<TResource> which is declared as follows:
public sealed record ResourceListResult<TResource>(IReadOnlyList<TResource> Items, long TotalCount);The Items property must contain the items with the filtering, sorting and pagination applied. Return the total number of matching records before pagination in the TotalCount property.
Returning results from create, update and delete
CreateAsync(), UpdateAsync() and DeleteAsync() return a ResourceOperationResult:
| Result | Meaning |
|---|---|
Success() | The record was saved or deleted. |
Success(key) | The record was saved, with the new record's key. Return this from CreateAsync() when the create page uses a custom model, so that a lookup can select the new record. |
NotFound() | The record doesn't exist any more. |
ValidationFailed(field, message) | The form is displayed again, with the error on that field. Pass null as the field for an error that isn't about one field. The field parameter is the model's property name, such as nameof(Supplier.Name) |
For an unexpected failure, throw an exception. The page displays a general error, and StellarAdmin logs the exception.
Returning validation errors
Typically we suggest that you handle validation errors using data annotations or a framework like FluentValidation. However, when you use a custom data source, you can also return validation errors from the CreateAsync() or UpdateAsync() methods.
For example, if your data source is a wrapper around a REST API, you'd want to map the API errors to the correct properties on your model. The code sample below maps the errors of a SupplierApiValidationException to the correct property names and return ValidationFailed() with all the validation errors.
public async Task<ResourceOperationResult> CreateAsync(
Supplier model, CancellationToken cancellationToken)
{
try
{
await api.CreateAsync(model, cancellationToken);
return ResourceOperationResult.Success();
}
catch (SupplierApiValidationException exception)
{
var errors = exception.Errors.Select(error =>
new ResourceValidationError(ToPropertyName(error.Field), error.Message));
return ResourceOperationResult.ValidationFailed(errors);
}
}
// Maps the API's field names to the model's properties
private static string? ToPropertyName(string? field) => field switch
{
"code" => nameof(Supplier.Code),
"name" => nameof(Supplier.Name),
_ => null,
};StellarAdmin displays each error under its field, like any other validation error. If the property's name is null, or the property isn't a field of the form, StellarAdmin displays the error at the top of the form.