Home > Software design >  Mapping a semi-structured JSON column into a class in EF Core 7
Mapping a semi-structured JSON column into a class in EF Core 7

Time:01-19

I would like to use the new JSON Columns feature of EF Core 7 to store and retrieve data in the following format in and from my PostgreSQL database:

{
    "Name": "Email_AND_Phone_OR_RootUser",
    "Rules": [
       ["HasEmail", "HasPhone"],
       ["IsRoot"]
    ]
 }

This array of string arrays has a dynamic length and the string arrays within it too. If i understand correctly, i should create an owned class, reference it in my entity and either add the appropriate data attribute or configure it OnModelCreating. In the examples i find in the internet, i don't see any use of lists or arrays within the JSON mapping class. Are the following mapping classes valid ?

public class Policy
{
    [MaxLength(30)] public string Name { get; set; } = null!;
    public List<List<string>> RuleBinding { get; set; } = new();
}

Or, as an array of string arrays:

public class Policy
{
    [MaxLength(30)] public string Name { get; set; } = null!;
    public string[][] RuleBinding { get; set; } = null!;
}

Also, is the use of JSON Columns appropriate in this case or not?

CodePudding user response:

EF Core library for PostgreSQL (Npgsql.EntityFrameworkCore.PostgreSQL) has it's own support for JSON which was build prior to EF Core 7 and EF 7 APIs are not supported yet - see JSON Mapping doc:

EF Core 7.0 introduced support for JSON columns. Npgsql's JSON support - detailed below - is different, and has been available since version 3.0. We plan to adopt EF's JSON support in version 8.0.

Both mapping should be supported AFAIK.

public class Policy
{
    [MaxLength(30)] public string Name { get; set; } = null!;
    [Column(TypeName = "jsonb")] public List<List<string>> RuleBinding { get; set; } = new();
}
  • Related