【问题标题】:Store string as jsonb column with npgsql使用 npgsql 将字符串存储为 jsonb 列
【发布时间】:2020-09-17 12:57:04
【问题描述】:

我有以下型号

public class Guardian
    {
        public int id { get; set; }
        public string username { get; set; }
        public string email { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public string gender { get; set ;}
        public string address { get; set; }

        public string Questions;

        public IList<Urgency> Urgencies { get; set; } = new List<Urgency>();
    }

我的 AppDbContext 上的这行代码:DbContext

builder.Entity<Guardian>().Property(d => d.Questions).HasColumnType(NpgsqlDbType.Jsonb);

我希望将 Questions 字符串字段作为 JsonB 类型存储在 postgreSQL 数据库中。我收到此错误:

Argument 2: cannot convert from 'NpgsqlTypes.NpgsqlDbType' to 'string'

这完全有道理,但不知道我应该如何处理它,我已经做过研究,但似乎没有针对我的特殊情况。我真的很感激一些建议。

【问题讨论】:

  • 快速尝试:根据docs,应该是HasColumnType("jsonb")
  • @NateBarbettini 非常感谢您

标签: c# .net-core entity-framework-core jsonb npgsql


【解决方案1】:

HasColumnType - 这是一个通用的 EF Core 方法 - 接受一个数据库类型名称是一个字符串(例如字符串 jsonb),而不是 Npgsql 特定的 NpgsqlDbType.Enum。你应该简单地改变你的代码如下:

builder.Entity<Guardian>().Property(d => d.Questions).HasColumnType("jsonb");

See the Npgsql EF Core provider docs 获取有关 JSON 映射的此信息和其他信息。

【讨论】:

    【解决方案2】:

    这可以通过使用DataAnnotation来完成:

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

    【讨论】:

      猜你喜欢
      • 2018-12-10
      • 2018-07-05
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      相关资源
      最近更新 更多