Working with multi-language database efficiently using EF Core.
- PostgreSQL
- SQL Server
Write : store all translations in the same colum as Json
{
"language": "value"
}
For default language the key is always "" (empty string).
Read : Using custom sql functions and call them from EF Core as static methods you can get The value in the language you want simply.
More details about create custom sql functions
- You should install the NuGet package :
dotnet add package Neptunee.EntityFrameworkCore.MultiLanguage
- Registration :
builder.Services.AddMultiLanguage<SampleDbContext>();
- Use
MultiLanguageProperty
to define props in entities/columns in tables :
public class Entity : BaseEntity
{
public MultiLanguageProperty Prop { get; set; }
}
- in
DbContext
override OnModelCreating to ConfigureMultiLanguageProperty
:
public class SampleDbContext: DbContext
{
/// ctors , DbSets ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ConfigureMultiLanguage(Database);
base.OnModelCreating(modelBuilder);
}
}
Write :
entity.Prop = new MultiLanguageProperty("defulte language","pew pew");
entity.Prop.Upsert("fr", "péw péw");
context.Add(entity);
await context.SaveChangesAsync();
Read :
context.Entities
.AsNoTracking()
.Select(e => new
{
Id = e.Id,
GetIn = e.Prop.GetIn(languageKey),
GetOrFirstIn = e.Prop.GetOrFirst(languageKey),
ContainsIn = e.Prop.ContainsIn(languageKey)
});
SQL Query :
-- @languageKey='fr'
SELECT e."Id",
MultiLanGetIn(e."Name", @languageKey) AS "GetIn",
MultilanGetOrFirstIn(e."Name", @languageKey) AS "GetOrFirst",
MultilanContainsIn(e."Name", @languageKey) AS "ContainsIn"
FROM "Entities" AS e;