Skip to content

Help to detect that a propery is stored in a JSON string #34568

Closed as not planned

Description

@JonPSmith

Users of my EfCore.SchemaCompare library want it to work on databases that uses entries that use JSON column mappings.

My EfCore.SchemaCompare library allows a developer to compare the DbContext.Model against an existing database and it tells you if there are differences between the two sources. The What does EfSchemaCompare check? section in to README tells what the library checks.

To do this I had to dig into all sorts EFCore's metadata and what they do (see EfSchemaCompare/Internal/Stage1Compare to get a feel what I did to create this library.)

I'm currently looking for metadata that tells me what properties are held in a JSON string, but I can't anything so far. I should say that I'm not as good developer as I used to be because I have dementia now (see this section in one of my articles).

What I have found so far

A JSON column is an Owned Type, which makes sense. However its not obvious how you know that it uses JSON columns. I'll keep looking.

Here is my test code

I don't think you need this, but these are the classes and DbContext I'm using at the moment.

classes

public class HeadEntry
{
    public int Id { get; set; }
    public int HeadInt { get; set; }
    public OuterJsonMap JsonParts { get; set; }

    /// <summary>
    /// Useful for debugging
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return $"{nameof(HeadInt)}: {HeadInt}, {nameof(JsonParts)}: {JsonParts}";
    }
}

public class OuterJsonMap
{
    public int OuterInt { get; set; }
    public string OuterString { get; set; }
    public DateTime OuterDate { get; set; }
    public InnerJsonMap InnerJsonMap { get; set; } = null!;

    /// <summary>
    /// Useful for debugging
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return $"{OuterInt}, {OuterString}, {OuterDate}, {InnerJsonMap}";
    }
}

public class InnerJsonMap
{
    public int InnerInt { get; set; }
    public string InnerString { get; set; }
    public DateTime InnerDate { get; set; }

    /// <summary>
    /// Useful for debugging
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return $"{InnerInt}, {InnerString}, {InnerDate}";
    }
}

public class Normal
{
    public int Id { get; set; }
    public string NormalString { get; set; }

    public int NormalExtraId { get; set; }

    public NormalExtra NormalExtra { get; set; }
}

public class NormalExtra
{
    public int NormalExtraId { get; set; }
    public string ExtraString { get; set; }
}

Test DbContext

public class JsonCustomerContext : DbContext
{

    public JsonCustomerContext(DbContextOptions<JsonCustomerContext> options)
        : base(options) {}

    public DbSet<Customer> Customers { get; set; }
    public DbSet<Normal> Normals { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().OwnsOne(
            headEntry => headEntry.JsonParts, ownedNavigationBuilder =>
            {
                ownedNavigationBuilder.ToJson();
                ownedNavigationBuilder.OwnsOne(contactDetails => contactDetails.Address);
            });
    }
}

Include provider and version information

EF Core version: 8.0.4
Database provider: all
Target framework: .NET 8.0
Operating system: Windows 10
IDE: Visual Studio 2022 17.11

Activity

  1. changed the title [-]Help to detect that a propery is stored in a JSON string (not urgent)[/-] [+]Help to detect that a propery is stored in a JSON string[/+] on Aug 31, 2024
  2. self-assigned this
    on Sep 5, 2024
  3. cincuranet commented on Sep 5, 2024

    @cincuranet
    Contributor

    You can use IsMappedToJson method for this. Here's an example based on your code:

    var customerEntity = db.Model.GetEntityTypes().First(x => x.Name == "ConsoleApp1.Customer");
    var navigation = customerEntity.GetNavigations().First(x =>x.Name == "JsonParts");
    Console.WriteLine(navigation.TargetEntityType.IsMappedToJson());

    This will print True because JsonParts is mapped using ToJson. For other properties it will return False.

  4. JonPSmith commented on Sep 6, 2024

    @JonPSmith
    Author

    HI @cincuranet,

    Thank you very much - that put me on the right track, and I'm getting there.

    I have some other questions if you don't mind:

    • The name of the column is taken from the property name, but can you change the name of the database string the OnModelCreating setup? I tried to do that in the OnModelCreating method, but couldn't find a way to do that.
    • Can you have multiple Json Mappings in one entity? e.g. Json1 and Json2.
  5. cincuranet commented on Sep 6, 2024

    @cincuranet
    Contributor

    Can you change the name of the database string? I tried to do that in the OnModelCreating method, but couldn't find a way to do that.

    What database string?

    Can you have multiple Json Mappings in one entity? e.g. Json1 and Json2.

    You mean Json1 and Json2 as properties in entity? Then the answer is yes.

  6. JonPSmith commented on Sep 6, 2024

    @JonPSmith
    Author

    Wow, quick. I edited my question, which I hope will be clear.

  7. cincuranet commented on Sep 6, 2024

    @cincuranet
    Contributor

    Yes. The ToJson method has overload that takes string.

  8. JonPSmith commented on Sep 9, 2024

    @JonPSmith
    Author

    Hi @cincuranet,

    Thanks for your help on this and I have got JsonMapping working. I'm closing this now, but I have some more things to do before I release EfCore.SchemaCompare 8.1.0.

  9. JonPSmith commented on Sep 28, 2024

    @JonPSmith
    Author

    Hi,

    I have reopen this issue as I have another issue about detecting if a an entity is using Json Mapping. In my first attempt I had a series of entries in hierarchically using Json Mapping. e.g.

    Head                            IsMappedToJson = true
         -| TopJson                 IsMappedToJson = true
               -| MiddleJson        IsMappedToJson = true
                     -| BottomJson  IsMappedToJson = FALSE
    

    In this case I know that the Bottom Json Mapping entry must be a Json Mapping.

    BUT I added a second Json Mapping entity to the Head to check it would work, e.g.

    public class HeadEntry
    {
        public int Id { get; set; }
        public TopJson JsonParts { get; set; }
        public ExtraJson ExtraJsonParts { get; set; }
    }  

    Then I get two Navigation, but the ExtraJson did have anything to tell me that this entity is using Json Mapping

    Entity Name: DataLayer.JsonColumnDb.HeadEntry
      Property = HeadInt, type = int
      1
      Navigation = ExtraJson, IsJson = False
         TargetEntityType = DataLayer.JsonColumnDb.ExtraJson, 
         DeclaringEntityType = DataLayer.JsonColumnDb.HeadEntry
      2
      Navigation = JsonParts, IsJson = True
         TargetEntityType = DataLayer.JsonColumnDb.TopJsonMap, 
         DeclaringEntityType = DataLayer.JsonColumnDb.HeadEntry
    

    Can you give me some help me to detect that the ExtraJson entity is using Json Mapping.

  10. roji commented on Sep 29, 2024

    @roji
    Member
  11. AndriySvyryd commented on Oct 3, 2024

    @AndriySvyryd
    Member

    @JonPSmith You need to call ToJson() on ExtraJsonParts for it to be mapped to JSON. This would map it to a separate JSON column:

            modelBuilder.Entity<Customer>().OwnsOne(
                headEntry => headEntry.ExtraJsonParts, ownedNavigationBuilder =>
                {
                    ownedNavigationBuilder.ToJson();
                });
    
  12. JonPSmith commented on Oct 7, 2024

    @JonPSmith
    Author

    Hi @AndriySvyryd

    What I want a simple DbContext to use in my testing my code to compare Json Mapping entities against a database. For my tests I have one entity that has two ToJson-type properties, e.g.

    public class HeadEntry
    {
        public int Id { get; set; }
        public int HeadInt { get; set; }
        public TopJsonMap TopJsonMap { get; set; }
        public ExtraJson ExtraJsonParts { get; set; }
    }

    And after trying various OnModelCreating Json Mappings code I found one that creates a database with the correct columns.

    modelBuilder.Entity<HeadEntry>().OwnsOne(
        headEntry => headEntry.TopJsonMap, ownedNavigationBuilder =>
        {
            ownedNavigationBuilder.ToJson();
            ownedNavigationBuilder.OwnsOne(x => x.MiddleJsonMap).ToJson()
                .OwnsOne(x => x.BottomJsonMap).ToJson();
        });
    modelBuilder.Entity<HeadEntry>().OwnsOne(
        headEntry => headEntry.ExtraJsonParts, ownedNavigationBuilder =>
        {
            ownedNavigationBuilder.ToJson();
        });

    BUT, when I save data with a SaveChanges it has a System.ArgumentNullException Value cannot be null. (Parameter 'key') . I have looked at this a lot, but can't find the problem is. Below is the the full logging for the test, which occurs when SaveChanges is called.

    Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
    Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
    SELECT 1
    Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
    IF SERVERPROPERTY('EngineEdition') <> 5
    BEGIN
        ALTER DATABASE [EfCore.SchemaCompare-Test_TestJsonColumns] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
    END;
    Executed DbCommand (14ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
    DROP DATABASE [EfCore.SchemaCompare-Test_TestJsonColumns];
    Executed DbCommand (127ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
    CREATE DATABASE [EfCore.SchemaCompare-Test_TestJsonColumns];
    Executed DbCommand (48ms) [Parameters=[], CommandType='Text', CommandTimeout='60']
    IF SERVERPROPERTY('EngineEdition') <> 5
    BEGIN
        ALTER DATABASE [EfCore.SchemaCompare-Test_TestJsonColumns] SET READ_COMMITTED_SNAPSHOT ON;
    END;
    Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
    SELECT 1
    Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
    CREATE TABLE [HeadEntries] (
        [Id] int NOT NULL IDENTITY,
        [HeadInt] int NOT NULL,
        [ExtraJsonParts] nvarchar(max) NULL,
        [TopJsonMap] nvarchar(max) NULL,
        CONSTRAINT [PK_HeadEntries] PRIMARY KEY ([Id])
    );
    An exception occurred in the database while saving changes for context type 'DataLayer.JsonColumnDb.JsonCustomerContext'.
    System.ArgumentNullException: Value cannot be null. (Parameter 'key')
       at System.Collections.Generic.Dictionary`2.FindValue(TKey key)
       at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
       at Microsoft.EntityFrameworkCore.Update.ModificationCommand.<GenerateColumnModifications>g__HandleJson|41_4(List`1 columnModifications, <>c__DisplayClass41_0&)
       at Microsoft.EntityFrameworkCore.Update.ModificationCommand.GenerateColumnModifications()
       at Microsoft.EntityFrameworkCore.Update.ModificationCommand.<>c.<get_ColumnModifications>b__33_0(ModificationCommand command)
       at Microsoft.EntityFrameworkCore.Internal.NonCapturingLazyInitializer.EnsureInitialized[TParam,TValue](TValue& target, TParam param, Func`2 valueFactory)
       at Microsoft.EntityFrameworkCore.Update.ModificationCommand.get_ColumnModifications()
       at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.AddParameters(IReadOnlyModificationCommand modificationCommand)
       at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.AddCommand(IReadOnlyModificationCommand modificationCommand)
       at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.TryAddCommand(IReadOnlyModificationCommand modificationCommand)
       at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.TryAddCommand(IReadOnlyModificationCommand modificationCommand)
       at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.CreateCommandBatches(IEnumerable`1 commandSet, Boolean moreCommandSets, Boolean assertColumnModification, ParameterNameGenerator parameterNameGenerator)+MoveNext()
       at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.BatchCommands(IList`1 entries, IUpdateAdapter updateAdapter)+MoveNext()
       at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
       at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<>c.<SaveChanges>b__112_0(DbContext _, ValueTuple`2 t)
       at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
       at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
       at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
    

    Here is my entities

    namespace DataLayer.JsonColumnDb;
    
    public class HeadEntry
    {
        public int Id { get; set; }
        public int HeadInt { get; set; }
        public TopJsonMap TopJsonMap { get; set; }
        public ExtraJson ExtraJsonParts { get; set; }
    }
    
    public class ExtraJson
    {
        public string ExtraString { get; set; }
        public int ExtraInt { get; set; }
    }
    
    public class TopJsonMap
    {
        public string TopString { get; set; }
        public MiddleJsonMap MiddleJsonMap { get; set; } = null!;
    }
    
    public class MiddleJsonMap
    {
        public string MiddleJsonString { get; set; }
        public BottomJsonMap BottomJsonMap { get; set; }
    }
    
    public class BottomJsonMap
    {
        public string BottomJsonString { get; set; }
    }

    Using EF Core 8

  13. AndriySvyryd commented on Oct 7, 2024

    @AndriySvyryd
    Member

    BUT, when I save data with a SaveChanges it has a System.ArgumentNullException Value cannot be null. (Parameter 'key') . I have looked at this a lot, but can't find the problem is. Below is the the full logging for the test, which occurs when SaveChanges is called.

    It's caused by the extra .ToJson() calls on the nested entity types.

    Change your code to:

    modelBuilder.Entity<HeadEntry>().OwnsOne(
        headEntry => headEntry.TopJsonMap, ownedNavigationBuilder =>
        {
            ownedNavigationBuilder.ToJson();
            ownedNavigationBuilder.OwnsOne(x => x.MiddleJsonMap)
                .OwnsOne(x => x.BottomJsonMap);
        });

    We'll detect this case in validation in future releases: #34816

  14. JonPSmith commented on Oct 8, 2024

    @JonPSmith
    Author

    Hi @AndriySvyryd,

    Thank you, that fixed it.

    I would say that there aren't much documentation about the configuration of the Json Mapping in the OnModelCreating part of the the DbContext, and if you get it wrong (like I did) its hard to work out what is wrong. I suggest you add a section called "Json Mapping" in the EF Core's "Create a model" section.

  15. roji commented on Oct 8, 2024

    @roji
    Member

    @JonPSmith that's a good suggestion - we're indeed lacking good docs on this. For EF 10 we'll hopefully also allow mapping JSON columns as complex types (as opposed to owned entities), at which point it would become the default/recommended way to do things. We should definitely provide good documentation on this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions