有没有办法在 EF Core Postgres JSON 中使用列表?

Is there a way to use list with EF Core Postgres JSON?

这在 PG 中是可能的:

public class Parent
{
  [Column(TypeName = "jsonb")]
  //Mode 1: a column in the table
  public Child[] Children { get; set; }
}

public class Child
{
  //Mode 2: a virtual column only existing in JSON
  public GrandChild[] GrandChildren { get; set; }
}

public class GrandChild
{
}

我的问题是是否有一种方法可以内联使用其他 CLR 类型而不是数组,例如 List<T>HashSet<T> 甚至只是 IList<T>ICollection<T> ,以便于访问并避免每次我们想要进行更改时重新创建集合,或者避免定义一堆其他代理属性。

我尝试将 HasConversion 设置为数组,但没有成功。

如果您启用 type plugins in Npgsql.Json.NET:

,此方法有效 "automatically"
NpgsqlConnection.GlobalTypeMapper.UseJsonNet();
using (var context = new MyContext(options.Options))
{
    var parent = new Parent()
    {
        Children = {
            new Child() {
                GrandChildren = {
                    new GrandChild() { Name = "A" },
                    new GrandChild() { Name = "B" }
                }
            }
        }
    };

    context.Add(parent);
    context.SaveChanges();

    foreach(var p in context.Parents.ToList()) {
        // This is just to print the whole object. You don't have to touch JSON.NET
        // yourself here, Npgsql will convert to/from .net types at 'the edges'.
        Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(p));
    }       
}


// Using these definitions
class MyContext : DbContext
{
    public MyContext(DbContextOptions<MyContext> options)
       : base(options)
    { } 
    public DbSet<Parent> Parents { get; set; }
}
public class Parent
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column(TypeName = "jsonb")]
    public List<Child> Children { get; set; } = new List<Child>();
}    
public class Child
{
    public List<GrandChild> GrandChildren { get; set; } = new List<GrandChild>();
}    
public class GrandChild
{
    public string Name { get; set; }
}