/Neptunee.EntityFrameworkCore.MultiLanguage

Working with multi-language database efficiently using EF Core.

Primary LanguageC#

Neptunee.EntityFrameworkCore.MultiLanguage

Working with multi-language database efficiently using EF Core.

icon

Supports

  • PostgreSQL
  • SQL Server

How It's Work ?

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

Setup

  • 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 Configure MultiLanguageProperty :
public class SampleDbContext: DbContext
{
    /// ctors , DbSets ...
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ConfigureMultiLanguage(Database);
        base.OnModelCreating(modelBuilder);
    }
}

Using

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;

More