How to bind dictionary in core for entity framework?

.net-core c# entity-framework entity-framework-core


My model includes a property that contains raw json values. I am using entity framework core 3 and dot net core 3.

public class PostData
    [Column("id"), Key]
    public int Id { get; set; }

    public string Name { get; set; }

    [Column("properties"), JsonExtensionData]
    public virtual Dictionary<string, object> Properties { get; set; } 

And I mapped in my db context.

    protected override void OnModelCreating(ModelBuilder modelBuilder)

        modelBuilder.Entity<PostData>(b =>
            b.Property(u => u.Properties)
                    d => JsonConvert.SerializeObject(d),
                    s => JsonConvert.DeserializeObject<Dictionary<string, object>>(s)

So When I post a data from core,

    "name": "x",
    "properties": {
        "color": "red",
        "size": "L"

Action is:

    public async Task<IActionResult> Create([FromBody] PostData data)
        await using var context = new MyDbContext();

        await context.Post.AddAsync(data);
        await context.SaveChangesAsync();

        return await Task.FromResult(Ok(data));

enter image description here

It saves properties to database like following.


Why does not serialize?

4/2/2020 11:42:52 AM

Popular Answer

I'm taking a shot in the dark here based on the presence of "ValueKind" in the data. ValueKind is a property of JsonElement in System.Text.Json. Everywhere else, you're using JSON.NET, and in particular, the JsonExtensionData attribute is from JSON.NET. I'd imagine that you haven't actually fully replaced System.Text.Json, and that, rather than JSON.NET, is being used during the model binding phase. See the migration guide for details on how to use JSON.NET instead.

4/2/2020 1:29:36 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow