Skip to content

Add support for persisting key properties on JSON-mapped entity types #28594

Description

@AndriySvyryd

However, this wouldn't allow persisting the values of keys that contain the ordinal property.

This depends on #34445 to allow flexibility in the order of values coming from the database

Activity

  1. added this to the Backlog milestone on Aug 10, 2022
  2. removed this from the Backlog milestone on May 6, 2023
  3. maumar commented on May 6, 2023

    @maumar
    Contributor

    sending for retriage since our plans for json + value types

  4. added this to the Backlog milestone on May 10, 2023
  5. roji commented on Apr 29, 2024

    @roji
    Member

    Some notes on this based on our recent design discussion in Redmond:

    Advantages

    • One value of this feature is stable partial updating of (ordered) lists within JSON documents.
      • With a list of complex types, any update/removal of an element can only occur given its index position.
      • If we implement partial updating of collections (as opposed to sending the full list on each update), then Index-based updates are problematic for concurrency: if two UoW sessions apply "delete the first position" concurrently, the first two elements of the list are deleted instead of just the first. A key-based delete would always only delete the desired instance.
      • Similar to other concurrency issues, this can be mitigated by having a concurrency token (on the containing entity type); but not having one is more likely to be a pit of failure for partial updates to lists than other cases.
      • Note that a similar problem already exists with primitive collections, where no key is possible.
    • Similarly, persistent keys would allow stable pointing to an element of a JSON list.
      • Note that this is useful only for elements within a JSON list. For JSON types not within a list, it's already possible to point to them (and update/delete them) without a key, so complex types are sufficient there.
    • Note that a user may decide that the position in the list is a suitable "identifier".
      • This includes usage scenarios where deletion and insertion is rare, and the array position has "meaning".
      • In these cases, simply using a list of complex types is the right solution.

    Issues

    • Many databases lack an easy ability to perform JSON operations based on a property within a list; while JSONPATH allows selecting elements of a list where some property is equal to some value, most databases don't support this.
      • It's probably possible to expand the list to a relational resultset (e.g. OPENJSON) and use regular operators - just as we do to translate LINQ queries over JSON lists.
      • While this should work well for querying (and so with navigations pointing to a specific owned entity embedded in some JSON list), it isn't clear whether this can be done for updating/removing; we'd probably have to extract the position of the element in order to pass it to the JSON modify/remove functions, which at the very least will probably be inefficient.
    • Even for regular querying, there's typically no mechanism for efficiently getting a list element whose (key) property is equal to something - the database would have to scan the list. This is in contrast to database primary keys, which are always back by an index.
    • Similarly, there is also no database uniqueness guarantee of the key properties.
      • It's worth remembering that for everything to work properly, keys must be unique across the elements (Posts) across all container entities (Blogs), which will likely be impossible to guarantee.
      • For example, one user could insert a Blog with a Post of key X, and another user could insert another Blog with another Post which also has the key X. At this point, the database is in a problematic state: if some user now loads both blogs, EF's change tracking will throw.
    • Our current modeling doesn't allow for a complex type to contain an (owned) entity type.
      • This means that if some user just wants to have some Posts with persistent keys within a JSON document, its containers inside the JSON must also have persistent keys all the way up - even if there's no such natural key.
      • This is a problem specifically when the containing chain to the JSON root contains non-lists; non-lists already provide stability, and keys are totally redundant - it's perfectly reasonable to reference a customer's "Shipping address" without that address having to have a persistent key (one can think of it as sharing the customer's key).
      • This problem could be mitigated by resorting to synthetic keys for the containing types (just like today), but those are problematic in various ways and force different semantics, just because the type needs to contain a list with persistent keys. A modeling where some structural types have keys and others don't - as opposed to today's stronger distinction between entity and complex types - could help, but would be a big change.

    @AndriySvyryd @ajcvickers let me know if I've missed something.

  6. 9 remaining items

  7. roji commented on Nov 20, 2025

    @roji
    Member

    For anyone upvoting here, we're interesting in understanding exactly why you'd like EF support for key properties within JSON, and what benefits you expect to get out of doing that. In other words, you can map JSON via a complex type that happens to have an Id property that's an ID in your business logic, without EF being aware of it being a key property (it would be treated like any other property).

    Note that when this issue was originally opened, complex type support for JSON did not exist; so I'm wondering whether this issue was simply for allowing having an Id property in JSON (which used to be blocked in owned JSON).

  8. jukkahyv commented on Nov 20, 2025

    @jukkahyv

    I can't remember exactly anymore, but I think my problem was actually the same as #29380. At some point, having a property named "Id" in the JSON property caused an error. That other issue linked to this one, but it seems it has been fixed independently? In general, I don't care if EF recognizes keys in my JSON properties, I simply don't want EF to have unnecessary restrictions on naming of properties in the JSON, which seems to have been fixed already. I can remove my vote here.

  9. lonix1 commented on Nov 21, 2025

    @lonix1

    If I remember correctly, my problem was the same as #35789 which was marked as a duplicate of this one. The JSON-mapped data could not use a property named Id so I need to use some other name, e.g. Key.

  10. GHMeyer0 commented on Nov 24, 2025

    @GHMeyer0

    In our case we have a Customer entity that owns collections of Phone and Email.

    We want to store those collections as JSON in the same table as Customer (using OwnsMany().ToJson()), and we don’t really need a business key on those JSON elements. Our only goal is to keep all customer contacts in the Customer table without having to create separate tables for Phone and Email.

    However, with the current behavior we are running into problems:

    • When we don’t define any key on Email/Phone, EF Core generates a shadow ordinal key (e.g. Email.Id).
      In our real application we use disconnected/no-tracking entities (API scenario). When we attach an updated Customer and try to save, we get:

      System.InvalidOperationException: The value of shadow key property 'Email.Id' is unknown when attempting to save changes. This is because shadow property values cannot be preserved when the entity is not being tracked. Consider adding the property to the entity's .NET type. See https://aka.ms/efcore-docs-owned-collections for more information.
      
    • If we follow the suggestion and add an Id to Email, we then get the opposite error:

      System.InvalidOperationException: 'Entity type 'Email' is part of a collection mapped to JSON and has its ordinal key defined explicitly. Only implicitly defined ordinal keys are supported.'
      

    So practically we end up with two choices:

    1. Stop using JSON and create separate tables for Email and Phone just to avoid these key issues; or
    2. Keep JSON but accept that in disconnected scenarios we will hit the shadow key error and can’t safely update the collection.

    What we would like is either:

    • Support for explicit keys on entities inside JSON-mapped collections (so we can map our own Id instead of the implicit ordinal), or
    • A way to use JSON-mapped owned collections in disconnected scenarios without EF depending on a shadow ordinal key that cannot be preserved.

    Our main requirement is simply: keep all customer contacts in the Customer row as JSON, without extra tables, and still be able to update those collections from detached entities without running into key-related exceptions.

    EntityTypeConfiguration

    using ETiino.Regras.Domain.Entities;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata.Builders;
    
    namespace ETiino.Regras.Infrastructure.EntityTypeConfigurations
    {
        public class CustomerEntityConfiguration : IEntityTypeConfiguration<Customer>
        {
            public void Configure(EntityTypeBuilder<Customer> builder)
            {
                builder.OwnsOne(p => p.Address, address =>
                {
                    address.Property(e => e.Street).IsRequired(false);
                    address.Property(e => e.Number).IsRequired(false);
                    address.Property(e => e.ZipCode).IsRequired(false);
                    address.Property(e => e.City).IsRequired(false);
                    address.Property(e => e.State).IsRequired(false);
                    address.Property(e => e.Neighborhood).IsRequired(false);
                    address.Property(e => e.Complement).IsRequired(false);
                });
    
                builder.OwnsMany(c => c.Phones, phones =>
                {
                    phones.ToJson();
                    phones.Property(t => t.Number).IsRequired();
                });
    
                builder.OwnsMany(c => c.Emails, emails =>
                {
                    emails.ToJson();
                    emails.Property(e => e.Address).IsRequired();
                });
            }
        }
    }

    Entities

    using System;
    using System.Collections.Generic;
    
    namespace ETiino.Regras.Domain.Entities
    {
        public class Customer
        {
            public Guid Id { get; set; }
    
            public string Name { get; set; }
            public Address Address { get; set; }
            public List<Phone> Phones { get; set; } = new();
            public List<Email> Emails { get; set; } = new();
        }
    
        public class Address
        {
            public string Street { get; set; }
            public string Number { get; set; }
            public string ZipCode { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public string Neighborhood { get; set; }
            public string Complement { get; set; }
        }
    
        public class Phone
        {
            public string Number { get; set; }
            public PhoneType? Type { get; set; } = PhoneType.Mobile;
            public ContactClassification Classification { get; set; } = ContactClassification.Main;
            public bool AllowWhatsApp { get; set; } = true;
            public bool AllowSms { get; set; } = true;
            public bool AllowCall { get; set; } = true;
        }
    
        public class Email
        {
            public string Address { get; set; }
            public ContactClassification Classification { get; set; } = ContactClassification.Main;
            public bool AllowSending { get; set; } = true;
        }
    
        public enum PhoneType
        {
            Mobile = 0,
            Landline = 1
        }
    
        public enum ContactClassification
        {
            Main = 0,
            Alternative = 1,
            Message = 2
        }
    }
  11. roji commented on Nov 24, 2025

    @roji
    Member

    @GHMeyer0 it sounds like you want to use the JSON complex type mapping introduced in EF 10 (link) - this allows mapping types to JSON without them having any sort of key/identity.

  12. jukkahyv commented on Nov 24, 2025

    @jukkahyv

    Sounds like the JSON complex type solves the problems for most people here, including myself. I'm excited to try EF 10, but I'm waiting for EFCore.NamingConventions nuget to be updated to 10.0.

  13. rhwork commented on Dec 17, 2025

    @rhwork

    For anyone upvoting here, we're interesting in understanding exactly why you'd like EF support for key properties within JSON, and what benefits you expect to get out of doing that. In other words, you can map JSON via a complex type that happens to have an Id property that's an ID in your business logic, without EF being aware of it being a key property (it would be treated like any other property).

    Note that when this issue was originally opened, complex type support for JSON did not exist; so I'm wondering whether this issue was simply for allowing having an Id property in JSON (which used to be blocked in owned JSON).

    I've come across the PR for deprecating JSON support for the Owned types (#37290) and it eventually led me to this thread but i'm not sure if this is the right place to raise this. We're implementing aggregate modelling in our solution and used Owned types for Entities within our aggregate root. Because Owned types have entity semantics they appear in the ChangeTracker.Entries() and have an EntityState of Added/Modified/Deleted. With the (imminent?) deprecating of JSON support I did a POC to move everything to use Complex Properties and found that the ChangeTracker support differed in this case and i'm assuming that's because Complex Properties have ValueObject semantics. I'm a bit lost as to how to proceed with the solution going forward, i.e stick with the Owned types and JSON even if it's going to be deprecated or migrate to Complex properties even though the semantics affect the Change Tracking behaviour.

    On a related note, how would the deprecation affect EF core targeting document databases? as I understand it they use Owned types out of the box?

  14. AndriySvyryd commented on Dec 17, 2025

    @AndriySvyryd
    MemberAuthor

    I've come across the PR for deprecating JSON support for the Owned types (#37290) and it eventually led me to this thread but i'm not sure if this is the right place to raise this. We're implementing aggregate modelling in our solution and used Owned types for Entities within our aggregate root. Because Owned types have entity semantics they appear in the ChangeTracker.Entries() and have an EntityState of Added/Modified/Deleted. With the (imminent?) deprecating of JSON support I did a POC to move everything to use Complex Properties and found that the ChangeTracker support differed in this case and i'm assuming that's because Complex Properties have ValueObject semantics. I'm a bit lost as to how to proceed with the solution going forward, i.e stick with the Owned types and JSON even if it's going to be deprecated or migrate to Complex properties even though the semantics affect the Change Tracking behaviour.

    The deprecation is not final, we are looking for feedback like this to determine how we proceed in EF 11.

    On a related note, how would the deprecation affect EF core targeting document databases? as I understand it they use Owned types out of the box?

    They would move to complex types as well.

  15. roji commented on Dec 18, 2025

    @roji
  16. rhwork commented on Dec 18, 2025

    @rhwork
  17. roji commented on Dec 18, 2025

    @roji
  18. rhwork commented on Dec 18, 2025

    @rhwork
  19. roji commented on Dec 18, 2025

    @roji
  20. self-assigned this
    on Feb 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions