dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.82k stars 3.2k forks source link

JSON: Allow weakly-typed mapping via Dictionary #29825

Open roji opened 1 year ago

roji commented 1 year ago

28871 tracks weakly-typed JSON mapping via JsonDocument/JsonElement, where the JSON document schema varies and so a strongly-typed model isn't appropriate.

We can also allow simply mapping arbitrary Dictionary types - this corresponds to how many people use

roji commented 1 year ago

Duplicate of #29427

ajcvickers commented 1 year ago

Re-opening, since dictionary mapping was not covered by "primitive collections".

vchirikov commented 8 months ago

Link to the "issue" should be in the docs at least, was difficult to find.. Is it planned for 9.0 release?

roji commented 8 months ago

@vchirikov the milestone generally expresses whether an issue is planned for a given release or not.

onionhammer commented 7 months ago

I assume this would also meant support for ExtensionData and Dictionary<string, JsonElement>?

roji commented 7 months ago

@onionhammer that would be a combination of this and #28871.

onionhammer commented 7 months ago

@roji putting querying aside for now, JsonElement can already be saved/serialized as an entity property, but Dictionary<string, JsonElement> cannot;

bugproof commented 6 months ago

is this why this isn't working ?

modelBuilder.Entity<Account>()
            .OwnsOne(c => c.Settings, d =>
            {
                d.ToJson();
                d.OwnsOne(a => a.ShippingRateMarkups);
            }).HasKey(c => c.AccountId);

///////////////////////////////
public class Account
{
    public string AccountId { get; set; }
    public Settings Settings { get; set; }
}

public class Settings
{
    public Dictionary<string, decimal>? ShippingRateMarkups { get; set; }
}

what's the alternative solution?

roji commented 6 months ago

@bugproof supporting mapping Dictionary<string, decimal> to JSON is what this issue tracked.

As a workaround, if all you want to do is save and load it to the database, you can use a value converter to do the JSON serialization/deserialization yourself. But this won't support querying into it, etc.

bugproof commented 6 months ago

And how will it be stored? As JSON instead of JSONB? Yes I don't need complex queries with it, just load/save as settings dictionary isn't very complex.

roji commented 6 months ago

As JSON instead of JSONB?

It's up to you to configure that database column type, as always - see the docs.