postgresql 传递一个列表给dapper以过滤或排除项目Postgres,其中不包含

ddrv8njm  于 2022-12-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(112)

C#要使用dapper在postgreSql查询上按Id过滤,可以使用"= ANY(:myList)",例如

await using var conn = new NpgsqlConnection(_dbContext.Database.GetConnectionString());
    await conn.ExecuteAsync(@"
        UPDATE books
        SET discount = :discount
        WHERE author_id = :authorIds
        AND book_id = ANY(:bookIds);
", new { discount = discountVal, authorId = author, bookIds = BookIdList });

等效于使用IN。
但在需要排除的情况下,不可能使用any(〈〉ANY()),因为它对每个ID执行OR操作。
在这种情况下,使用简单的NOT IN会带来类型问题,因为我的ID是uuid,如果尝试将lost转换为string,int也会出现同样的情况,
x一个一个一个一个x一个一个二个x
",new {折扣=折扣值,作者ID =作者,书籍ID =字符串. Join(",",书籍ID列表.选择(x =〉$"('{x}')")});

which brings type comparison issues like "Npgsql.PostgresException: 42883: operator does not exist: uuid <> text"
avwztpqn

avwztpqn1#

在尝试了一些数组操作之后,我能够使它像这样工作

await using var conn = new NpgsqlConnection(_dbContext.Database.GetConnectionString());
    await conn.ExecuteAsync(@"
        UPDATE books
        SET discount = :discount
        WHERE author_id = :authorIds
        AND book_id NOT IN (SELECT unnest(:bookIds));
", new { discount = discountVal, authorId = author, bookIds = BookIdList });

相关问题