简体   繁体   English

将半结构化 JSON 列映射到 EF Core 7 中的 class

[英]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:我想使用 EF Core 7 的新 JSON 列功能在我的 PostgreSQL 数据库中存储和检索以下格式的数据:

{
    "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.这个字符串数组 arrays 具有动态长度,其中也包含字符串 arrays。 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.如果我理解正确,我应该创建一个拥有的 class,在我的实体中引用它并添加适当的数据属性或将其配置为 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?在我在 inte.net 中找到的示例中,我没有看到在 JSON 映射 class 中使用列表或 arrays。以下映射类是否有效?

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:或者,作为字符串数组 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?另外,在这种情况下使用 JSON 列是否合适?

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 : PostgreSQL ( Npgsql.EntityFrameworkCore.PostgreSQL ) 的 EF Core 库本身支持 JSON,它是在 EF Core 7 之前构建的,目前尚不支持 EF 7 API - 请参阅JSON 映射文档

EF Core 7.0 introduced support for JSON columns. EF Core 7.0 引入了对 JSON 列的支持。 Npgsql's JSON support - detailed below - is different, and has been available since version 3.0. Npgsql 的 JSON 支持 - 详见下文 - 是不同的,并且从 3.0 版开始可用。 We plan to adopt EF's JSON support in version 8.0.我们计划在 8.0 版本中采用 EF 的 JSON 支持。

Both mapping should be supported AFAIK. AFAIK 应该支持这两种映射。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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