Entity Framework Core jsonb 列类型

问题描述 投票:0回答:3

我正在使用 Entity Framework Core 和 npgsql postgresql for Entity Framework Core。

我的问题是,使用迁移,如何标记类属性以生成 JSONB 列类型?

例如:

public class MyTableClass
{
    public int Id { get; set; }

    // My JSONB column
    public string Data { get; set; }
}

提前致谢。

c# postgresql entity-framework-core npgsql
3个回答
43
投票

基于 H. Herzl 评论:

我最终的解决方案是这样的:

public class MyTableClass
{
    public int Id { get; set; }

    [Column(TypeName = "jsonb")]
    public string Data { get; set; }
}

迁移产生了这个:

Data = table.Column<string>(type: "jsonb", nullable: true),

使用迁移更新数据库时,使用 jsonb 类型正确创建了数据列。

谢谢 H. Herzl!


21
投票

按照@bruno.almeida的建议使用

string
是一个很好的解决方案,但无法查询.

其他方法是使用:

  • 作为 System.Text.Json DOM 类型(
    JsonDocument
    或 JsonElement)
  • 作为强类型的用户定义类型 (POCO)

JsonDocument
是我最喜欢的,因为它可以查询,设置灵活且快速,例如:

public JsonDocument Customer { get; set; }

更多详情:https://www.npgsql.org/efcore/mapping/json.html


0
投票

除了@bruno.almeida 的回复之外,值得注意的是,可以将类型添加到 JSONB 列。例如,我最近一直在创建一个列来保存各种文件上传错误:

我有一个

RecordErrors
类,我认为它足够通用,可以用于我的许多错误存储情况:

public class RecordErrors
{
    public IEnumerable<ResultError> Errors { get; set; } = Enumerable.Empty<ResultError>();
}

ResultError
类只有额外的属性,例如
ErrorCode
Message
,但如果您想要简单的字符串错误值,可以很容易地用
String
替换。

我的实体看起来像这样:

public class MyFileUpload
{
    public int Id { get; set; }

    [StringLength(800)]
    public string Name { get; set; } = string.Empty;
    ...

    [Column(TypeName = "jsonb")]
    public RecordErrors? Errors { get; set; } = null;
}

运行迁移创建了具有

jsonb
类型的列。

然后您可以使用以下常规方式将数据保存到数据库:

 _databaseContext.SaveChangesAsync(cancellationToken);

在我的实例中,数据库中的结果是 JOSN,看起来像:

{
  "Errors": [
    {
      "Code": "Columns.Unsupported",
      "Message": "The upload contains the following unsupported column headings: Column 1, Column 2, Column 3, Column 4."
    }
  ]
}
© www.soinside.com 2019 - 2024. All rights reserved.