【问题标题】:Is there a way to use list with EF Core Postgres JSON?有没有办法将列表与 EF Core Postgres JSON 一起使用?
【发布时间】:2020-07-07 16:34:54
【问题描述】:

这在 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 设置为数组,但没有成功。

【问题讨论】:

    标签: c# json postgresql entity-framework-core npgsql


    【解决方案1】:

    如果您启用type plugins in Npgsql.Json.NET,这将“自动”工作:

    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; }
    }
    

    【讨论】:

    • 感谢您的回答。新的 .NET Core System.Text.Json 不是提供了该功能吗?只是好奇。顺便说一句,您是否必须将所有Id 列与DatabaseGenerated 关联?这不是按惯例解释的吗?
    • 你可以制作自己的 Npgsql 类型插件,使用 System.Text.Json 而不是 Json.Net,我敢肯定。或者也许已经存在一个。问题是数据库驱动程序必须了解如何对数据库的字段值进行编码。
    猜你喜欢
    • 1970-01-01
    • 2018-03-15
    • 2016-11-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多