PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Query json di Entity Framework Core PostgreSQL

Penso che tu stia cercando qualcosa come il seguente:

class Program
{
    static async Task Main(string[] args)
    {
        await using var ctx = new BlogContext();
        await ctx.Database.EnsureDeletedAsync();
        await ctx.Database.EnsureCreatedAsync();

        var lang = "es";

        var collection = await ctx.Settings
            .Where(s => EF.Functions.JsonExists(s.SettingValue, lang))
            .Select(s => new
            {
                s.SettingId,
                s.SettingParentId,
                SettingValue = s.SettingValue.GetProperty(lang).GetString()
            })
            .ToListAsync();

        foreach (var i in collection)
        {
            Console.WriteLine($"{i.SettingId}: {i.SettingValue}");
        }
    }
}

public class BlogContext : DbContext
{
    public DbSet<Setting> Settings { get; set; }

    static ILoggerFactory ContextLoggerFactory
        => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(@"Host=localhost;Username=test;Password=test")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Setting>().HasData(new Setting
        {
            SettingId = "1",
            SettingValue = JsonDocument.Parse(@"{ ""es"" : ""valor""}").RootElement
        });
    }
}

public class Setting
{
    public string SettingId { get; set; }
    public string SettingParentId { get; set; }
    public JsonElement SettingValue { get; set; }
}