简体   繁体   中英

Entity Framework Core PostgreSQL json query

Always return empty results

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

I try return only key from json but always return empty, when remove "select" works fine but i need only one key

This is the model

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

I think you're looking for something like the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM