Data Localization
Local texts translate the texts of the application: labels, messages, the names of enumeration values. The data that users enter, e.g. the name of a product category, a region or a role, is a different matter, as it changes at run time and lives in the database. Serenity can keep translations of such fields, show the values in the language of the user in lists, lookups and joined columns, and edit them in the localization tab of an entity dialog.
There are two ways to keep the translations:
[SharedLocalization] |
[LocalizationRow] |
|
|---|---|---|
| Where | One shared loc_DataTranslations table per database |
A localization table for each row, e.g. ProductLang |
| Needs | A [Localizable(true)] on each field to translate |
A row class with the same fields and a culture field |
| Fields | String fields | The fields of the localization row with the same name |
| IDs | short, int, long, Guid or string |
Any |
The shared table needs no table or row class per entity, so it is the simpler choice for new code, e.g. for the many small tables with a name, like types and categories. The localization table of a row is kept for the rows that already use it. Both work the same way in dialogs, lists and lookups.
Shared Translations Table
A row opts in with [SharedLocalization], and each field to translate gets [Localizable(true)], which is
System.ComponentModel.LocalizableAttribute:
[NorthwindConnection, NorthwindModule, TableName("Region")]
[LookupScript, SharedLocalization(LocalizeListByDefault = true)]
public sealed class RegionRow : Row<RegionRow.RowFields>, IIdRow, INameRow
{
[PrimaryKey, IdProperty]
public int? RegionID { get => fields.RegionID[this]; set => fields.RegionID[this] = value; }
[Size(50), NotNull, QuickSearch, NameProperty, Localizable(true)]
public string? RegionDescription { get => fields.RegionDescription[this]; set => fields.RegionDescription[this] = value; }
// ...
}
Only string table fields can be localized this way, and the row must have an ID of type short, int, long, Guid or
string. A row that has both [SharedLocalization] and [LocalizationRow], or a [Localizable(true)] field that is
not a string table field, fails when it is first used, with a message that tells why.
The translations are kept in the loc_DataTranslations table, one row per record, field and language:
| Column | |
|---|---|
EntityType |
The row identifier of the row, e.g. Northwind.Region |
EntityIdInt, EntityIdGuid, EntityIdString |
The ID of the record, in the column of its type |
FieldName |
The property name of the field, e.g. RegionDescription |
LanguageId |
The language, e.g. de or de-DE |
Value |
The translation |
UpdateDate, UpdateUserId, UpdateUsername |
Who changed it last and when |
The two ID columns that a record doesn't use have placeholder values (0, an empty GUID and "-"), so that none of them
is null and one unique index works the same way on every database. Renaming the property of a localized field, or the
row itself, which changes its row identifier, leaves its translations behind under the old name.
The Table in Each Database
The table has to be in the same database as the rows it translates, as a list query reads the translations from it. It
is created by DataTranslationsMigration of Serenity.Extensions. That migration targets no real database, but the
db:DataTranslations tag (DataTranslationsMigration.Tag), which the DataMigrations of the application requests for
each database that has a row with [SharedLocalization]:
// DataMigrations.AddMigratorServices, in the Configure<RunnerOptions> callback
if (DataTranslationsMigration.IsNeededIn(databaseKey, typeSource, sqlConnections))
options.Tags = [.. options.Tags, DataTranslationsMigration.Tag];
IsNeededIn resolves the connection key of each such row through the connection key fallbacks, so a row of a module
whose key falls back to Default gets the table in the default database. The Serene and StartSharp templates have this
line. A database that is migrated by another runner gets the table by requesting the same tag.
Localization Table of a Row
The LocalizationRowAttribute maps a
row to a localization row that stores per-language values, e.g. the Northwind ProductRow:
[CaptureLog(typeof(ProductLogRow))]
[LocalizationRow(typeof(ProductLangRow), LocalizeListByDefault = true)]
public sealed class ProductRow : Row<ProductRow.RowFields>, IIdRow, INameRow
{
// ...
}
The localization row must implement ILocalizationRow,
which requires a culture ID field, and have a field for the ID of the localized record (MappedIdField, by default the
name of the ID property of the row):
public interface ILocalizationRow : IIdRow
{
StringField CultureIdField { get; }
}
A field of the row is localizable when the localization row has a field with the same name, unless one of them has
[Localizable(false)].
Editing Translations
The LocalizationBehavior and
SharedLocalizationBehavior handle the translations with the save, retrieve and delete handlers of the row:
- A retrieve request with
"Localizations"in itsIncludeColumnsreturns the translations inRetrieveResponse.Localizations, a dictionary of rows by language with the translated fields set. - A save request saves the translations in
SaveRequest.Localizations, in the same shape. A field sent empty removes its translation. A translation can only be saved for a field that the user can edit, so a field permission can't be bypassed through the translations. - Deleting a record removes its translations, unless it is soft deleted.
LocalizablePropertyProcessor marks the properties of these fields as Localizable, and an entity dialog shows its
localization tab for them, with the languages of TranslationConfig.getLanguageList(). A dialog of your own can use
createDataTranslationsField of Pro.Extensions, an input for each language that edits the translations of one value.
Load the record with Retrieve and IncludeColumns: ["Localizations"], not from a list whose values may be translated,
and send the values back with Localizations.
Lists, Joined Fields and Lookups
LocalizeListByDefault decides whether the values are shown translated without being asked for:
- Lists. The list handler (with Pro.Extensions) returns the translated value of each localized field in the
language of the user, or in one of its fallback languages (e.g.
de-DE, thende), or else the original value. The translation is part of the SQL query, so sorting, filtering and the quick search work on the translated values.ListRequest.Localizeoverrides it: an empty string or"false"for the original values,"true"for the language of the user, or a language ID, e.g."de-DE". - Joined fields. A field of another row whose
[Origin]is a localizable field of a joined row is translated the same way, e.g.RegionDescriptionof a territory, orCategoryNameof a product. Only one level of joins is followed, through a[ForeignKey(typeof(...))]and a[LeftJoin]. - Lookups. The lookup script of the row is generated and cached for each language, with the localizable fields it selects translated, so lookup editors show the translated names.
Leave LocalizeListByDefault off for a row whose records are found by their text, e.g. a lookup item looked up by its
name in code, as a translated value wouldn't match. Its lists can still be translated by asking for it with
ListRequest.Localize.
Rows Loaded in Your Own Code
A row that is loaded with connection.List or a query of your own is not translated, as only the list handler and the
lookup script do it. DataTranslationStore.ApplyTranslations translates such rows with one query, and
LocalizationRowTranslations.Apply does the same for a row with a localization table:
var regions = connection.List<RegionRow>(q => q.Select(r.RegionID, r.RegionDescription));
DataTranslationStore.ApplyTranslations(connection, regions, DataTranslationLanguages.Current(localTextRegistry));
DataTranslationLanguages.Current gives the language of the current UI culture and its fallback languages, from the
local text registry, or from the parent cultures when it is null. Pass the fields that were loaded as the last argument
when the query left some localizable fields out, so that they don't get a value.
Testing
In tests with an in-memory SQLite database, db.CreateDataTranslationsTable(connectionKey) of Serenity.Testing creates
the shared table in the shape the migration creates it, for code that reads rows with [SharedLocalization].