4

In a .NET 7 Web API project, I try to use EF7 JSON column to store translations of the entity.

These are my entities:

public class Card
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<CardTranslation> Translations { get; set; }
}

public class CardTranslation
{
    public int laungaugeId { get; set; }
    public string Name { get; set; }
}

public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options{}

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Card>().OwnsMany(card => card.Translations).ToJson(); 
    }

    public virtual DbSet<Card> Cards { get; set; }
}

And in the Post action method, I accept the data in any language and in the Get action method also return data with the same language I entered for string values.

Sample of the request:

{
  "name": "你好",
  "translations": [
    {
      "laungaugeId": 0,
      "name": "你好"
    }
  ]
}

My issue with that : it stores data in SQL Server with Unicode as shown in the screenshot.

Could I configure serialization options to handle this issue?

MsSql Server Table

I'm expected to find the characters to be stored in the database as entered like English characters which is stored as is and doesn't get converted to Unicode

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Welcome to the joy of System.Text.Json. _By default, the serializer escapes all non-ASCII characters. That is, it replaces them with \uxxxx where xxxx is the Unicode code of the character._ Ref: [How to customize character encoding with System.Text.Json](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/character-encoding) – AlwaysLearning Nov 11 '22 at 02:40
  • Thanks For your advice but I try To set System.Text.Json Configuration In Program.cs Like Below And The Issue Still Exists. builder.Services.Configure(options => { options.WriteIndented = true; options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); }); – Ahmed Hesham Nov 11 '22 at 15:04
  • currently there is no way to customize the serializer. Support for it is tracked here: [dotnet/efcore#28043](https://github.com/dotnet/efcore/issues/28043) – VahidN Mar 12 '23 at 06:19

0 Answers0