简体   繁体   中英

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 inte.net, 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM