Skip to content

Entity mapped to JSON returns different byte[] when not the whole entity is projected #33435

Closed
npgsql/efcore.pg
#4067

Description

@frencsi

Sample code

var user = new User
{
    Vault = new UserVault
    {
        PasswordHash = RandomNumberGenerator.GetBytes(64)
    }
};

await using var context = new TestDbContext();
await context.Users.AddAsync(user);
await context.SaveChangesAsync();

var vaultProjection = await context.Users
    .AsNoTracking()
    .Where(x => x.Id == user.Id)
    .Select(x => x.Vault)
    .FirstAsync();

var passwordHashProjection = await context.Users
    .Where(x => x.Id == user.Id)
    .Select(x => x.Vault.PasswordHash)
    .FirstAsync();

var customProjection = await context.Users
    .Where(x => x.Id == user.Id)
    .Select(x => new { PasswordHash = x.Vault.PasswordHash })
    .FirstAsync();

var c1 = vaultProjection.PasswordHash.SequenceEqual(user.Vault.PasswordHash);

var c2 = passwordHashProjection.SequenceEqual(user.Vault.PasswordHash);

var c3 = customProjection.PasswordHash.SequenceEqual(user.Vault.PasswordHash);

Console.WriteLine($"c1:{c1}\nc2:{c2}\nc3:{c3}");

public class TestDbContext : DbContext
{
    public DbSet<User> Users => Set<User>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer("Server=localhost;Database=test;User=SA;Password=Password123@;Encrypt=false")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasKey(user => user.Id);

        modelBuilder.Entity<User>().OwnsOne(user => user.Vault).ToJson();
    }
}

public class User
{
    public int Id { get; set; }

    public UserVault Vault { get; set; }
}

public class UserVault
{
    public byte[] PasswordHash { get; set; }
}

Generated queries

1.:

SELECT TOP(1) [u].[Vault], [u].[Id]
FROM [Users] AS [u]
WHERE [u].[Id] = @__user_Id_0

2.:

SELECT TOP(1) CAST(JSON_VALUE([u].[Vault], '$.PasswordHash') AS varbinary(max))
FROM [Users] AS [u]
WHERE [u].[Id] = @__user_Id_0

3.:

SELECT TOP(1) CAST(JSON_VALUE([u].[Vault], '$.PasswordHash') AS varbinary(max)) AS [PasswordHash]
FROM [Users] AS [u]
WHERE [u].[Id] = @__user_Id_0

Results

c1: true
c2: false
c3: false

Second & third query returns a larger completely different byte array.

Versions

EF Core version: 9.0.0-preview.2.24128.4
Database provider: Microsoft.EntityFrameworkCore.SqlServer version: 9.0.0-preview.2.24128.4
.NET version: 9.0.100-preview.2

Activity

  1. frencsi commented on Mar 30, 2024

    @frencsi
    Author

    Also tested with 9.0.0-preview.1.24128.4 and 8.0.3 versions, same queries and results.

  2. self-assigned this
    on Mar 30, 2024
  3. roji commented on Mar 30, 2024

    @roji
    Member

    Duplicate of #30981

  4. roji commented on Mar 30, 2024

    @roji
    Member

    Confirmed.

    Our byte[] representation inside JSON is base64; since SqlServerByteArrayTypeMapping uses our standard JsonByteArrayReaderWriter, everything works well when we're serializing the entire document (SaveChanges) or deserializing the entire document (load the entire JSON document).

    But when a byte[] is queried as a JSON scalar, we use JSON_VALUE() and apply a type conversion (CAST(JSON_VALUE([u].[Vault], '$.PasswordHash') AS varbinary(max))), but SQL Server's conversion to varbinary(max) doesn't work with base64, but rather with SQL Server's specific format for binary data. Note that OPENJSON with WITH does do base64.

    We knew about all this when implementing the primitive collection support in 8.0 - see #30981 and #31261; in #31261 we even blocked byte[] usage in contexts where ordering needs to be preserved, and so OPENJSON with WITH cannot be used. However, we forgot the non-collection case where simple JSON_VALUE() is used, which suffers from the same problem.

    Concrete next steps IMHO are to block usage of JSON_VALUE() for varbinary (including possible patching) - the current situation causes data corruption. Longer-term, the solution here would be to switch to using OPENJSON for simple property access - with CROSS APPLY - instead of JSON_VALUE() (this is #30981).

  5. frencsi commented on Mar 31, 2024

    @frencsi
    Author

    Oh, I was searching in the issues in the wrong way. Thank you for explaining! :)

  6. roji commented on Mar 31, 2024

    @roji
    Member

    Keeping this issue for now tracking fixing this for binary specifically - for using OPENJSON for other types (e.g. nvarchar(max) we can keep using #30981.

  7. added 3 commits that reference this issue on Apr 12, 2024
    cb2e6fe
    fe5a512
    1ef51cf
  8. added a commit that references this issue on Apr 16, 2024
    ef5f7a3
  9. added this to the 9.0.0 milestone on Apr 16, 2024
  10. modified the milestones: 9.0.0, on Apr 29, 2024
  11. modified the milestones: , 9.0.0 on Oct 12, 2024
  12. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions