SQL Server Marking Dictionary property as JSON column

nszi6y05  于 2023-04-04  发布在  其他
关注(0)|答案(1)|浏览(129)
public class AuditLog
{
    public int Id { get; set; }

    [MaxLength(65536)]
    public IDictionary<string, object> AuditData { get; set; }
}

Is it possible with EF Core 7 support for JSON columns to make this AuditData property to be JSON column? I am using SQL Server.

fnvucqvd

fnvucqvd1#

Yes it's possible but you have to configure it in the context not using the annotations.

You will need to add the package Microsoft.EntityFrameworkCore.SqlServer.Json then use the HasJsonConversion method in your DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AuditLog>()
        .Property(e => e.AuditData)
        .HasConversion(
            v => JsonSerializer.Serialize(v, null),
            v => JsonSerializer.Deserialize<Dictionary<string, object>>(v, null))
        .HasColumnType("json");
}

相关问题