.Net EF Core在postgresql使用jsonb类型进行查询问题集

1、Npgsql对 .NET 类型(如 List、Dictionary<string,object> 等)与 PostgreSQL 的 json/jsonb 字段的自动映射和序列化/反序列化,解决linq 转化成sql

解法:NpgsqlConnection.GlobalTypeMapper.EnableDynamicJson();

https://github.com/npgsql/efcore.pg/issues/2939


2、此属性修改变更后,状态没有跟踪为modify状态

解法:
OnModelCreating下新增:

builder.Entity<MajorVersion>()
        .Property(e => e.Tag)
        .HasConversion(
            v => System.Text.Json.JsonSerializer.Serialize(v, (System.Text.Json.JsonSerializerOptions)null),
            v => System.Text.Json.JsonSerializer.Deserialize<List<string>>(v, (System.Text.Json.JsonSerializerOptions)null)
        )
        .Metadata.SetValueComparer(new ValueComparer<List<string>>(
           (c1, c2) => c1.SequenceEqual(c2),
           c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v != null ? v.GetHashCode() : 0)),
           c => c == null ? null : c.ToList()
        ));
posted @ 2025-06-25 09:01  Cody&  阅读(50)  评论(0)    收藏  举报