Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mapping a semi-structured JSON column into a class in EF Core 7

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading