EFTranslatable is a light weight simple struct/type to allow your Entity/Model properties to be easily translated.
EFTranslatable is available on NuGet , GitHub
dotnet add package EFTranslatable
The following code demonstrates basic usage of EFTranslatable:-
The required steps to make a model translatable are:
- First, you need to allow
DbContext
to know aboutEFTranslatable
, in yourDataContext
file, inOnModelCreating
method add the following:-
using EFTranslatable;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.WithTranslatable(this);
}
public DbSet<Post> Posts { get; set; }
- Next, you should Drive from
HasTranslations<T>
whereT
is the currentModel
. - Next, Add
Translatable
to the property you want to be translatable. - Finally, you should make sure that all translatable properties are set to the
text
-datatype in your database. If your database supportsjson
-columns, use that.
using EFTranslatable;
public class Post : HasTranslations<Post>
{
public uint Id { get; set; }
public Translatable Title { get; set; } = new();
public Translatable Content { get; set; } = new();
}
There is two ways of making a Translatable
:
- By passing a
Dictionary
where is theKey
is the locale and theValue
is the transaltion. - Or by passing
Json
string directly .
public void Create()
{
_context.Posts.Add(new Post()
{
Title = new Translatable(new Dictionary<string, string>()
{
{"en","Good Title"},
{"ar", "عنون جيد"}
}),
Content = new Translatable("{\"en\": \"Good Content!\",\"ar\": \"شغال\"}"),
});
_context.SaveChanges();
}
public void Update()
{
var post = _context.Posts.First();
post.Title.Set("Different Title", "en").Set("New Locale", "fr");
// If locale is null , the Current `Thread` locale will be used
post.Content.Set("This is the current locale content");
_context.SaveChanges();
}
using EFTranslatable.Extensions;
public void Equality()
{
// Will use the Current `Thread` locale
var post = _context.Posts.WhereLocalizedEquals(x => x.Title, "Good Title").SingleOrDefault();
//Will use the giving Locale
var post2 = _context.Posts.WhereLocalizedEquals(x => x.Title, "عنون جيد", "ar").SingleOrDefault();
}
public void Contains()
{
// Will use the whole `Json` string for checking
var post = _context.Posts.WhereLocalizedContains(x => x.Title, "Good Title").SingleOrDefault();
//Will use the giving Locale string value for checking
var post2 = _context.Posts.WhereLocalizedContains(x => x.Title, "عنون جيد", "ar").SingleOrDefault();
}
using EFTranslatable.Extensions;
[HttpGet]
public IActionResult Single()
{
var post = _context.Posts.WhereLocalizedEquals(x => x.Title, "Good Title").SingleOrDefault();
return Ok(post?.Translate("ar"));
}
[HttpGet]
public IActionResult Multiple()
{
var posts = _context.Posts.Select(x => x.Translate("ar")).ToList();
return Ok(posts);
}
The MIT License (MIT). Please see License File for more information.