gpt4 book ai didi

c# - 如何在 Npgsql.EntityFrameworkCore 中查询具有 JSON 数组的列

转载 作者:行者123 更新时间:2023-12-04 15:16:07 26 4
gpt4 key购买 nike

笔记:

  • 使用 Npsql.EntityFrameworkCore.PostgreSQL v3.1.4
  • 使用 Npgsql v4.1.3.1
  • 使用代码优先方法

  • 我有下表(称为汽车):
    enter image description here
    它有两列:
  • LicenseNumber(输入文本)(在 Car.cs 模型中输入字符串)
  • KitchenIntegrations(类型 jsonb)(类型 Car.cs 中的 List)
    其中集成是集成类型的列表。

  • Car 类看起来像这样:
    public class Car
    {
    public string LicenseNumber {get;set;}

    public List<Kitchen> KitchenIntegrations {get;set;}
    }
    Kitchen.cs 看起来像这样:
    public class Kitchen
    {
    public int Id {get;set;}

    public string KitchenName {get;set;}
    }
    最后我的 CarContext.cs 看起来像这样:
    public class CarContext : DbContext
    {
    public DbSet<Car> Cars { get; set; }

    public CarContext()
    {
    }

    public CarContext(DbContextOptions<CarContext> options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    optionsBuilder.UseNpgsql("ConnectionStringGoesHere");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    modelBuilder.HasDefaultSchema("public");

    modelBuilder.Entity<Car>(
    builder =>
    {
    builder.HasKey(i => i.LicenseNumber);
    builder.Property(i => i.KitchenIntegrations).HasColumnType("jsonb").IsRequired(false);
    }
    );
    }
    }
    汽车 表我只需要获取 Id = 1 的 KitchenIntegration。
    我可以在 PSQL 中轻松完成此操作,但在尝试查询 JSON 数组时遇到问题。
    我试过:
    var integrations = context.Cars.Select(i => i.KitchenIntegrations.First(o => o.Id == 1)).ToList();
    但是遇到无法将其转换为 SQL/PSQL 的问题。
    所以我的问题是如何遍历 EntityFrameworkCore 中的数组或 JSON 列表? (如果可能的话,只将它作为服务器端而不是客户端来做)。
    谢谢!任何帮助是极大的赞赏!

    最佳答案

    我的 2 美分。
    假设您有一张 table fixtures具有以下结构。(Id, JsonProperty) .
    假设您在数据库中有一条像这样的记录。

    1, [{"Name": "Test", "Value": "123"}, {"Name": "Test2", "Value": "pesho"}]
    2, [{"Name": "Test", "Value": "321"}, {"Name": "Test2", "Value": "pesho"}]
    3, [{"Name": "Test", "Value": "1123"}, {"Name": "Test2", "Value": "pesho"}]
    然后使用 EF Core 3.1Npgsql.EntityFrameworkCore.PostgreSQ 3.14你可以做:
        var search = "[{\"Value\": \"123\"}]";
    var result = dbContext.Fixtures
    .FirstOrDefault(s => EF.Functions.JsonContains(s.JsonProperty, search));
    var search2 = "[{\"Name\": \"Test\"}]";
    var multipleResults = dbContext.Fixtures
    .Where(s => EF.Functions.JsonContains(s.JsonProperty, search2));

    关于c# - 如何在 Npgsql.EntityFrameworkCore 中查询具有 JSON 数组的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64297975/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com