Skip to content

Stop escaping Unicode characters unnecessarily in relational JSON #32152

Open
@ajcvickers

Description

@ajcvickers

The JSON stored in a SQL Server column always has its Unicode characters escaped. For example, this code:

context.Add(new Customer { Json = new MyJson { Be = "Füzér Castle in the Zemplén Mountains" } } );
await context.SaveChangesAsync();

Results in the following JSON in the database:

{"Be":"F\u00FCz\u00E9r Castle in the Zempl\u00E9n Mountains"}

However, there is nothing preventing the JSON being stored as:

{"Be":"Füzér Castle in the Zemplén Mountains"}

EF reads the correct string back in both cases, but other tools may not be expecting escaped JSON for all Unicode characters.

Test code:

using (var context = new SomeDbContext())
{
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();

    context.Add(new Customer { Json = new MyJson { Be = "Füzér Castle in the Zemplén Mountains" } });

    await context.SaveChangesAsync();
}

using (var context = new SomeDbContext())
{
    foreach (var c in context.Set<Customer>().ToList())
    {
        Console.WriteLine(c.Json.Be);
    }
}

public class SomeDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Data Source=(LocalDb)\MSSQLLocalDB;Database=AllTogetherNow")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().OwnsOne(e => e.Json).ToJson();
    }
}

public class Customer
{
    public int Id { get; set; }
    public MyJson Json { get; set; }
}

public class MyJson
{
    public string? Be { get; set; }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions