Localized business data

Overview

Localization switches the UI strings; this extension switches the business data: the same product, article or message shows Chinese content on a Chinese UI and English content on an English UI.

Business entities need no extra columns and admin pages need no code changes. There is only one convention: the default-language value stays on the entity's own field, every other language goes into that entity's own translation table (named feedback_lang by default).

Which language each place reads:

  • Admin list (AdminTable): the entity's own fields, i.e. the default language. Every language is entered at once in the edit dialog, so the list does not follow the UI language;
  • Edit dialog: the fields to translate become language tabs, each tab being exactly the template the page wrote;
  • Queries you write yourself (public list pages, domain services, reports, exports): chain .FromLang() onto an ISelect<T> and reading, filtering, sorting, paging and counting all happen on the translated basis;
  • CMS front-office content: hooked up automatically when the CMS extension is installed, no registration needed — see "Localized CMS content" below.

Without this extension, pages behave exactly as before and no translation table is created.

Who decides the "current UI language": in the back office it is the language chooser in the upper-right corner (a cookie); in the front office it can be the URL instead (/Feedback Chinese, /en-US/Feedback English) — see Language Routing. The parameterless .FromLang() reads the current UI language, so once that switch is on the front office follows the URL automatically and no query code changes.

Usage

1. Reference the extension

This extension is not published to the public NuGet feed; it is included for paid source-code licensees. For source integration use a ProjectReference:

<ProjectReference Include="..\Extensions\EasyAdminBlazor.MultiLang\EasyAdminBlazor.MultiLang.csproj" />

2. Register the entities that take part

One registration names two types: the business entity plus its translation entity.

builder.AddEasyAdminBlazor(new EasyAdminBlazorOptions { ... })
    .AddEasyAdminBlazorMultiLang(o =>
    {
        o.Entity<Feedback, FeedbackLang>();
        o.Entity<Product, ProductLang>();

        // pass a string to override the derived table name (lowercase letters, digits and underscores only)
        o.Entity<Article, ArticleLang>("sys_multi_lang");
    });

Register your own business entities here; the CMS content, categories and page elements are registered by the CMS extension itself.

The translation entity is an ordinary class you write, next to the business entity (in the Demo: EasyAdminBlazor.Demo/Entities/FeedbackLang.cs):

namespace EasyAdminBlazor.Demo.Feedbacks;

/// <summary>Non-default-language translations of a feedback row: one row = one message in one language.</summary>
public class FeedbackLang : IDataLangEntity
{
    /// <summary>Primary key of the business row (points at feedback.Id).</summary>
    public long RowId { get; set; }

    /// <summary>Language code, stored as the full culture name (e.g. en-US).</summary>
    public string Lang { get; set; } = string.Empty;

    // Everything else is a translatable field: the property name must match the business entity,
    // length and type are not declared a second time here — table creation copies them from the source property
    public string Subject { get; set; } = string.Empty;

    public string Content { get; set; } = string.Empty;
}

Rules for this class:

  • It must implement IDataLangEntity (defined in the main package, no extra reference needed). The interface pins exactly two key columns, RowId (long) and Lang (string); a wrong name or type is a compile error. Both must be public properties — an explicit interface implementation raises at registration.
  • The translatable field list = the string properties other than RowId / Lang. Each name must exist on the business entity as a public readable/writable string property; otherwise registration throws and names the entity and the property.
  • Length and type are copied from the matching business-entity property by default: varchar(2000) on the entity means varchar(2000) on the translation column, [Column(DbType = "text")] means text. To size a translation column differently (wider or narrower), write [Column] on the translation property — what you declare there wins.
  • Table name precedence: the explicit name passed at registration > [Table(Name = "...")] on the translation class > <snake(entity)>_lang derived from the business entity (Feedback → feedback_lang).
  • Physical table and column names must be lowercase letters, digits and underscores (feedback_lang, row_id, subject). Without [Column(Name = ...)] they are generated from the property name (Subject → subject); an invalid name raises at registration and shows the name to write.
  • Tables are created automatically at startup, per registered entity, including new columns — no hand-written DDL; every other database instance (every dedicated or shared ORM instance under multi-tenancy) gets them when it is assembled, not lazily. Unregistered entities get no table.
  • Adding a field to translate = add it to the business entity + add the same-named property to the translation class + restart (the column is added). Adding it only to the business entity leaves the translation table without that column.

Where the default language comes from: the language whose values live on the entity's own fields (everything else goes to <entity>_lang) is the default language the site already declares, in appsettings.json — the extension does not ask for it a second time:

{
  "BootstrapBlazorOptions": {
    "DefaultCultureInfo": "zh-CN",
    "SupportedCultures": ["zh-CN", "en-US"]
  }
}

When DefaultCultureInfo is absent it is derived in this order: the UI culture at process startup (parent codes fold into SupportedCultures, zh → zh-CN) → the first SupportedCultures entry. Different machines or base images can derive different results, so declare it explicitly on a production site.

Changing it later loses nothing (languages without translations fall back to the entity field); what changes is which tab counts as "the original" in the edit dialog and which script an untranslated row falls back to.

The lang column stores the full culture name (en-US), exactly as written in SupportedCultures.

3. Edit dialog: put the fields into AdminDataLangEditor

The template binds the business entity's properties and every language tab reuses it; layout, controls and grid widths all stay with the template:

<EditTemplate>
    <div class="row form-inline g-3">
        <div class="col-12 col-sm-6 col-md-4">
            <BootstrapInput @bind-Value="context.Name" />
        </div>
    </div>
    @* With the extension installed and this entity registered, the block below becomes "中文 / English" tabs;
       without it only the main row renders, exactly like a page with no localization *@
    <AdminDataLangEditor Row="context">
        <ChildContent Context="lang">
            <div class="col-12 col-sm-6 col-md-4">
                <BootstrapInput @bind-Value="lang.Subject" />
            </div>
            <div class="col-12">
                <Textarea @bind-Value="lang.Content" rows="4" />
            </div>
        </ChildContent>
    </AdminDataLangEditor>
</EditTemplate>
  • Context="lang" is a Razor requirement: a nested template may not reuse the outer EditTemplate's context name (RZ9999). On the default-language tab, lang is the very object the edit dialog holds.
  • The number of tabs = SupportedCultures minus the default language; with a single language there are no tabs.
  • Only the fields written in this template are ever collected. A field present in the translation class but absent here stays empty and falls back to the default-language value when read; a field on the entity that is not in the translation class does not take part at all.
  • Rich text is written as usual, <AdminEditor @bind-Value="lang.Content" />; the tab gets the same editor (real rich text with the TinyMCE extension, a multi-line box otherwise).

4. Reading translations: .FromLang()

The admin list always shows the default-language originals and is not mapped. In queries you write yourself (public list pages, domain services, reports, exports), chain FromLang() onto the ISelect<T>:

var rows = await repo.Select
    .FromLang()                                        // translations in the current UI language
    .Where(a => a.Subject.Contains("Apple"))           // filtering happens on the translation
    .OrderByDescending(a => a.Id)
    .Include(a => a.Org)                               // navigations keep working
    .IncludeMany(a => a.Items)
    .Page(1, 20)
    .ToListAsync();

var total = await repo.Select.FromLang().CountAsync();  // counting uses the same basis

// Pin one language (an English mail body, a single-language export) without touching the thread culture
var english = await repo.Select.FromLang("en-US").ToListAsync();

A translatable column reads as "translation first, empty translation falls back to the entity's own field", so untranslated rows show the default-language value automatically.

  • No if needed: for an unregistered entity, or when the language requested is the default one, FromLang() returns the very same query object.
  • Without an argument it reads the current UI language (CultureInfo.CurrentUICulture): pages follow the visitor; [Scheduler] jobs and mail templates, which have no request context, use the process default.
  • Write the code in FromLang("en-US") as a full culture name; a parent code "en" folds into the entry in SupportedCultures. Passing the default language, or a language the site does not support, leaves the query unchanged.
  • Chain it anywhere: before or after Where both work; conditions, sorting, paging and global filters such as soft delete keep working.
  • It exists on single-entity queries only: orm.Select<T>() / repo.Select. Joined queries (orm.Select<T1, T2>()) do not carry it — query each side separately if both need translations.
  • It applies to the main query only: fields brought in by Include / IncludeMany stay in the default language. For a related entity that needs translations too, run its own Select<T>().FromLang().
  • To read the default-language originals (edit prefill, compare-before-write) use repo.Select without FromLang.

A clickable example: the Demo's EasyAdminBlazor.Demo/Pages/FeedbackList.cshtml — open /Feedback ("Feedback" in the top nav); the page header states which language was actually read, and ?lang=en-US demonstrates pinning one.

Configuration

Option Default Notes
Entity<TEntity, TLang>(string? tableName = null) — Register one entity: the business entity plus its translation entity. The translation entity decides the translatable field list; the table name is derived from the business entity unless you pass a name

Mistakes raise at startup and name the entity. The common ones:

  • the business entity's primary key is not long;
  • the translation entity does not implement IDataLangEntity, or implements RowId / Lang explicitly;
  • a property of the translation entity has no matching public readable/writable property on the business entity, or that property is not string;
  • the translation entity has no translatable property;
  • two registrations hit the same translation table or the same business entity, or one translation entity is shared by two business entities;
  • a physical table or column name is not lowercase letters/digits/underscores.

Scope

Place Which language Notes
Admin list / filter / sort / paging / count / export default AdminTable is not mapped; each language is entered in the edit dialog's tabs
Quick search box default Still searching the entity's own fields
Original fields in the edit dialog default So translations never leak back into the default-language columns
Language tabs in the edit dialog one per tab The default-language tab binds the main row, the others one row each; cancelling saves nothing
A hand-written query chaining .FromLang() UI language (or the pinned one) Translations apply at SQL level, so filtering by an English value matches a row named in Chinese; sorting / paging / counting share the basis
CMS public pages (ICmsContentService, <vc:element>) UI language See below; with no extension installed they read the default-language originals
CMS admin list / edit prefill default Same basis as every other admin list

An interface language may be given as a parent culture (en); it folds into the corresponding SupportedCultures code (en-US). When it cannot be folded, or folds to the default language, the query is not rewritten.

Schema

One table per registered entity, named <snake(entity)>_lang by default. feedback_lang:

Column Notes
row_id Primary key of the business row (points at feedback.Id), part of the key
lang Language code (full culture name), part of the key, varchar(20)
subject Translation of Feedback.Subject, sized from the source property (varchar(100) here)
content Translation of Feedback.Content, same rule (varchar(2000), or text when the source is text)

(row_id, lang) is the primary key: one row is "one record in one language". The business table feedback itself is untouched.

To index one language column separately (heavy filtering on the English title, say) write [Index] on the translation entity as usual.

Localized CMS content

The three content kinds shipped by the CMS extension — content (cms_data), categories (cms_category) and page elements (cms_element) — work as soon as the site has both the CMS extension and this extension installed, with no registration to write. Without this extension, CMS public pages, admin editing and inline editing behave exactly as before.

1. The host only registers its own business entities

builder.AddEasyAdminBlazor(new EasyAdminBlazorOptions { ... })
    .AddEasyAdminBlazorCms()
    .AddEasyAdminBlazorMultiLang(o =>
    {
        // only this site's own business entities go here;
        // cms_data_lang / cms_category_lang / cms_element_lang are contributed by the CMS extension
        o.Entity<Product, ProductLang>();
    });

Either wiring order gives the same result. Hosts that already wrote those three lines can keep them: the same pair under the same table name collapses into one registration instead of failing; only the same pair registered under two different table names throws.

Which fields are translatable:

Content Where the default language lives Translation table Translatable fields
Content CmsData.Title / Summary / Content / SeoTitle / SeoKeyword / SeoDescription cms_data_lang the same six
Category CmsCategory.Name / SeoTitle / SeoKeyword / SeoDescription cms_category_lang the same four
Page element CmsElement.ContentCn cms_element_lang ContentCn (the column in the translation table is content_cn as well)

The element body column keeps the name ContentCn and means "the default-language body" — switching the site's default language does not require renaming it.

In the content, category and element dialogs, title/name, summary, body and the three SEO fields are already wrapped into language tabs; everything else (slug, category, sort, image, custom fields) stays where it was.

2. Public pages read per language, admin pages stay in the default language

  • Public pages (lists, details, previous/next, related items, <vc:element> page elements) read translations in the UI language and fall back to the default-language originals where nothing is translated; the public keyword search matches English titles too.
  • Admin lists and edit prefill always read the default-language originals; each language is entered in the dialog's language tabs.
  • Inline page editing (the visual editor under "CMS > page elements") writes to the language the preview page is currently showing: switch the preview to English to fix English copy. Editing in a Chinese preview only writes Chinese, so the two never overwrite each other.
  • First-visit auto-insert of page elements is unchanged: an element that already exists is never written again, so a first English visit cannot push the page's default markup into the content column.

3. Upgrading an existing CMS site (breaking change)

At compile time: the hardwired "Chinese / English" columns are removed, so code referencing them no longer compiles (the CMS package version goes to 2.7.0; the last published one was 2.5.1):

Removed Replaced by
CmsData.TitleEn, CmsData.ContentEn title / content in cms_data_lang
CmsCategory.NameEn name in cms_category_lang
CmsElement.ContentEn content_cn in cms_element_lang
CmsItemView.TitleEn / ContentEn, CmsItemSave.TitleEn / ContentEn the same

Front-end templates never read *En, so they are unaffected; sites with custom code reading these fields have to move to the translation tables or the language tabs.

In the database:

  • The three SEO values moved out of the Data JSON into real columns (seo_title / seo_keyword / seo_description on cms_data / cms_category); initialization backfills the old JSON values into empty columns automatically, filling only empty columns and never overwriting. This happens whether or not the localization extension is installed;
  • Data keeps the business custom fields (price, stock, cover image, …), which are not translated;
  • The old hardcoded English values are not migrated — re-enter them in the dialog's language tabs if you need them;
  • The old *En columns are not dropped automatically; they are inert leftovers, drop them by hand if you care.

4. Out of scope

The business custom fields inside Data JSON (price, stock, …) are not stored per language; comments stay as they are; category names in dropdowns and the tree picker stay in the default language (admin basis).

Notes

  • Only registered entities have a translation table; FromLang() on anything else returns default-language values. The four CMS tables (content / category / page element / page-level SEO in cms_page_seo_lang) are registered by the extension itself and work as soon as it is installed.
  • The CMS page manager can preview in another language (the language dropdown in the toolbar, shown only when EnableLangRoute is on): switching to English reloads the iframe as /en-US/..., and saving writes the English translation — the lang marker on the rendered block and the read path share one vocabulary, so nothing has to be re-entered elsewhere.
  • Keep the two read paths apart: the front end reads per UI language (FromLang() / translate: true), while an admin edit dialog reads the default-language row and each language tab loads its own copy per row (AdminDataLangEditor). Running the admin read through the translated query shows English on the "中文" tab, and one save then writes English into the default-language columns.
  • Switching to a language tab prefills untranslated fields with the default-language value — that is exactly what the visitor would see; as long as you do not touch it, saving writes nothing and no row is inserted for it.
  • An empty translation means fall back to the default language; changing an existing translation to an empty string removes it (the column goes empty, and the row is deleted once every column in it is empty).
  • Translations are saved in the same transaction as the main row: if the main row commits and a translation fails, the whole save rolls back — no "row without translations" half-state.
  • Custom OnSaveAsync needs one extra call: pages using AdminTable's built-in save write translations automatically; pages that open their own transaction (the three CMS tables and the page-level SEO panel, CmsPageSeoService.SaveAsync, do) must call IDataLangSavePlugin.SaveAsync(uow.Orm, entity) inside that transaction right after writing the main row. Otherwise the language tab was edited, the dialog says "saved", and no translation reached the database.
  • Fields in the language tabs take no part in required-field validation (that only covers the default-language copy); labels are identical, just without the required asterisk.
  • Hard-deleting a business row does not delete its translation rows (soft delete keeps them, so restoring from the recycle bin brings the translations back). Clean up manually by row_id if you really want.
  • Translation column names are data: subject in feedback_lang.subject comes from the property name, so renaming the translation entity's property renames the column and old translations stop being reachable. Pin it with an explicit [Column(Name = "subject")] if that worries you. Renaming the business entity's property does not affect the translation table, as long as the translation property still matches the new name (a mismatch raises at registration).
  • The business table's column naming does not affect translation reads: even without an underscore-naming convention configured, SeoTitle still picks up the translation from cms_data_lang.seo_title.
  • A translation column takes its size from the source property when the table is created: whether an existing table follows a later change of the source field's size depends on the database provider's SyncStructure — do not treat it as a migration mechanism. To size it differently, write [Column(StringLength = ...)] on the translation property.
  • Multi-tenancy: translation tables are created when each IFreeSql instance is assembled — the main database by the extension initializer, every tenant database by the framework's FreeSqlConfigurator callback. Table names, column names and sizes are the same in the main database and every tenant database. Translations live in "the database the query ran against", routed exactly like the business rows. This cannot rely on UseAutoSyncStructure: FreeSql only syncs structure on writes, and a translation table in a tenant database may never be written to (nobody recorded a translation there) while every front-end read joins it — a missing table means a page-wide 500 (no such table: xxx_lang).