Selecting a related record

Select the record a foreign key refers to, with a lookup or a choice editor

StellarAdmin lets people select a related record on a form, such as a booking's traveller.

Using foreign keys on EF Core resources

A foreign key, such as Booking.TravellerId, stores the key of a related record. On an EF Core resource, when you add the foreign key property to a form, StellarAdmin will display a lookup editor, which allows users to select the related record from the referenced resource.

StellarAdmin finds the related resource from the relationship in your EF Core model. The property must be a foreign key in that model, which EF Core recognizes by convention, from [ForeignKey] or from HasForeignKey(). The entity the foreign key refers to, such as Traveller, must be registered as a resource. If either isn't the case, StellarAdmin renders the property with its default editor, such as a text or number input.

The example below registers travellers as a resource, and adds TravellerId to the booking create page:

admin.AddEfCoreResource<Traveller>(resource => { /* ... */ });

admin.AddEfCoreResource<Booking>(resource =>
{
    resource.AllowCreate(create => create.Fields(fields =>
    {
        fields.Add(booking => booking.TravellerId);
    }));
});

Add the foreign key property, not the navigation property. booking => booking.Traveller isn't a property EF Core maps, so StellarAdmin removes it from the form and reports a configuration problem. If the entity has only the navigation property, add a foreign key property, such as TravellerId, to it.

The field is labeled with the related resource's name, Traveller, and displays the selected traveller. Its Choose traveller button opens a sheet that lists the travellers, and searches them as people type. The title, description and media of each traveller, and how the sheet searches and sorts them, come from the title and reference information of the Traveller resource.

The booking create page with the traveller lookup's sheet open, searched for Walker, listing each traveller with their email address

Using a choice editor instead of a lookup

A lookup suits a long list, such as travellers. For a short list, such as a trip's guide, one of the choice editors (such as a select or radio group) may be better suited. StellarAdmin lists the guides from the Guide resource, as it does for a lookup.

fields.Add(trip => trip.LeadGuideId).UseRadioGroupEditor(radio => radio.Columns(3));
The trip's lead guide as a radio group that lists the guides in three columns

Configuring the lookup

To configure the lookup, call UseLookupSheetEditor(). Call Field() to configure the field that is displayed on the form, and Sheet() to configure the sheet that opens to the side, allowing users to select a record.

The example below displays the selected traveller using in input field, and sets the sheet's title and search hint:

using StellarAdmin.Resources.Editors;

fields.Add(booking => booking.TravellerId).UseLookupSheetEditor(lookup =>
{
    lookup.Field(field => field.Layout = LookupSheetEditorLayout.Input);
    lookup.Sheet(sheet =>
    {
        sheet.Title = "Choose a traveller";
        sheet.SearchPlaceholder = "Name or email";
    });
});
The traveller lookup with the selected traveller in a single row, and the sheet titled Choose a traveller with the search hint Name or email

The Field() builder callback has the following members:

MemberDescription
LayoutConfigures how the selected record is displayed: LookupSheetEditorLayout.Input displays its media and title in a single row, and Card adds its description in a taller row. The default is Card when the records have a description, and Input otherwise.
EmptyTextSets the text of the button while nothing is selected. The default is "Choose traveller", named after the field's label.
AllowClearSets whether people can clear the selection. The default is null, which allows it when the field is optional.
ShowMediaSets whether the selected record's media is displayed. The default is true.

The Sheet() builder callback has the following members:

MemberDescription
TitleSets the sheet's title. The default is the field's label.
SearchPlaceholderSets the hint text in the search input.
MinimumSearchLengthSpecifies the number of characters people must type before the sheet searches. The default is 0, which lists the records when the sheet opens.
PageSizeSets the number of records loaded at a time. The sheet displays a Load more button to load more records. The default is 20.
ShowMediaSets whether each record's media is displayed. The default is true.

Creating a record from a lookup

Sometimes users must have the ability to create a new record from the lookup. Enable this using the EnableCreate() method. This adds a New button, which opens the create page of the related resource in a sheet, and selects the new record when it's saved:

fields.Add(booking => booking.TravellerId).UseLookupSheetEditor(lookup =>
{
    lookup.EnableCreate();
});

The New button is displayed beside Choose traveller while nothing is selected, and inside the sheet when a search finds nothing.

The traveller lookup with a New button beside Choose traveller

The related resource must have a create page, enabled with AllowCreate(). If it doesn't, StellarAdmin doesn't display the button. Also, only users who are authorized to create new records for the related resource will see the button.

On a form model that wraps the entity, a foreign key that the field reads through the entity, such as form.Booking.TravellerId, is rendered as a lookup, just as it is on the entity itself.

A property of the form model itself, or of a form model that you save with a handler, isn't part of your EF Core model, so StellarAdmin doesn't know which resource it refers to. For these, call UseResource() with the related resource's type.

The example below adds a lookup for the form model's TravellerId property:

fields.Add(form => form.TravellerId).UseLookupSheetEditor(lookup =>
{
    lookup.UseResource<Traveller>();
});

Selecting records that aren't a resource

Sometimes you may not want to register EF Core entities that are used purely for lookup purposes as their own resources in StellarAdmin. You can still use these entities for lookup purpose on other resources by calling the UseItems<TEntity>() method on the lookup or choice builder.

Let's, for example, take the case where you have a Country entity on your EF Core model which is not registered as a resource. This entity is referenced by the CountryId field on your Destination resource.

When declaring the CountryId field, call UseItems<Country>(), and specify the expressions to use for the value and title of those entities in the lookup:

using StellarAdmin.EntityFrameworkCore;

fields.Add(destination => destination.CountryId).UseSelectEditor(select =>
{
    select.UseItems<Country>(country => country.Id, country => country.Name);
});

You can add further configuration using the items builder callback. The example below displays each country's ISO code in a lookup, and searches both the name and the code when the user uses the search box in the lookup sheet:

fields.Add(destination => destination.CountryId).UseLookupSheetEditor(lookup =>
{
    lookup.UseItems<Country>(
        country => country.Id,
        country => country.Name,
        items => items
            .UseCode(country => country.IsoCode)
            .SearchOn(country => country.Name, country => country.IsoCode));
});

The callback has these members:

MemberDescriptionAvailable in
Choice editorsLookups
OrderBy()Orders the records by a property. Without it, a lookup orders the records by their title, and a choice editor lists them in the order the database returns them.YesYes
UseDescription()Displays a description under each record's title.YesYes
UseAvatar(), UseCode(), UseIcon(), UseImage()Displays an avatar, a short code, an icon or an image beside each record's title.YesYes
UseGroup()Groups the records under headings.YesNo
SearchOn()Sets the properties the search matches. The default is the title.NoYes
UseDbContext<TContext>()Loads the records from another DbContext.YesYes
Where()Filters the records by the values of other fields on the form. See filtering options by another field.YesYes

Selecting records from another service

You can also allow looking up records from another source by creating a custom lookup source. The lookup source derives from LookupSource<TItem, TValue>, where TItem is the type of the records and TValue is the type of the value the field stores.

It must implement these members:

MemberDescription
GetValue()Returns the value the field stores for a record.
GetTitle()Returns a record's title.
FindAsync()Returns the records with the given values, which are the records already selected. Leave out the values that have no record.
SearchAsync()Returns a page of the records that match the search.

SearchAsync() receives a LookupQuery, which Term property holds the search term, or null when the search input is empty. The Skip and Take properties hold the page of records to return. It returns a LookupPage, with the records and whether more records follow them.

To display a description with each record, override GetDescription(). To display media, override one of GetAvatar(), GetCode(), GetIcon() or GetImage().

The example below looks up airports with an AirportClient, and displays each airport's code beside its city:

using StellarAdmin.Resources.Editors;

public class AirportSource(AirportClient client) : LookupSource<Airport, string>
{
    public override string GetValue(Airport airport) => airport.Code;

    public override string GetTitle(Airport airport) => airport.City;

    public override string? GetCode(Airport airport) => airport.Code;

    public override Task<IReadOnlyCollection<Airport>> FindAsync(
        IReadOnlyCollection<string> values,
        CancellationToken cancellationToken)
    {
        return client.FindAsync(values, cancellationToken);
    }

    public override async Task<LookupPage<Airport>> SearchAsync(
        LookupQuery query,
        CancellationToken cancellationToken)
    {
        // Loads one more airport than the page holds, to find out whether more follow
        var airports = await client.SearchAsync(
            query.Term, query.Skip, query.Take + 1, cancellationToken);

        return new LookupPage<Airport>(
            airports.Take(query.Take).ToList(),
            airports.Count > query.Take);
    }
}

To use the lookup source, call UseSource() with its type:

fields.Add(guide => guide.HomeAirport).UseLookupSheetEditor(lookup =>
{
    lookup.UseSource<AirportSource>();
});

StellarAdmin resolves the lookup source from dependency injection. If it isn't registered, StellarAdmin creates it, with the services its constructor takes.

On this page