将 Npgsql ADO 实体框架与 jsonb 一起使用

时间:2021-07-09 12:58:18

标签: c# .net postgresql entity-framework-6

我的测试数据库是基于这个

create table test 
(
    id int primary key, 
    b text, 
    i int, 
    name_1 text, 
    name_2 text, 
    alt_names jsonb
);

我通过 nuget 添加了 EntityFramework6.Npgsql,看起来它包含了一些依赖项

Installed Nuget

当我首先使用数据库构建数据模型时,我可以看到除 alt_names jsonb 列之外的每一列。

此页面 Supported Types and their Mappings 表明默认支持 jsonb。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

当你直接拉取为 jsonb 时,它可能无法如愿获得,或者它可能会作为错误返回。另外,如果我是你,我会先创建视图。如果你有问题,你可以改变nuget。 Postgresql 代码:

create or replace view public.testview 
as select
t.id,
t.b,
t.i,
t.name_1,
t.name_2,
json_build_object('alt_names', t.alt_names) as alt_names
from test t;

c# 代码:

  using Npgsql;
  using System;
  using System.Collections.Generic;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using System.Threading.Tasks;
  namespace ConsoleApp1
  {
  class Program
  {
      static void Main(string[] args)
      {
          
          var cs = "Host=localhost;Username=postgres;Password=123456;Database=postgres";

          using var con = new NpgsqlConnection(cs);
          con.Open();

          var sql = "select * from public.testview";

          using var cmd = new NpgsqlCommand(sql, con);
          NpgsqlDataReader dr = cmd.ExecuteReader();
          List<object> list = new List<object>();
          var i = 0;
          while (dr.Read())
          {
              while (i<dr.FieldCount)
              {
                  list.Add(dr[i]);
                  i++;
              }               
          }
          Console.WriteLine(list[5].ToString());
          //"{\"alt_names\" : \"test\"}"
      }


  }
  }