How to bind dictionary in asp.net core for entity framework?

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

Question

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

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

    [Column("name")]
    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)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<PostData>(b =>
        {
            b.Property(u => u.Properties)
                .HasConversion(
                    d => JsonConvert.SerializeObject(d),
                    s => JsonConvert.DeserializeObject<Dictionary<string, object>>(s)
                )
                .HasMaxLength(5000)
                .IsRequired();
        });
    }

So When I post a data from asp.net core,

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

Action is:

    [HttpPost("create")]
    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.

{"color":{"ValueKind":3},"size":{"ValueKind":3}}

Why does not serialize?

1
0
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.

2
4/2/2020 1:29:36 PM


Related Questions





Related

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