【问题标题】:No operator matches the given name and argument type. You might need to add an explicit type cast没有运算符与给定名称和参数类型匹配。您可能需要添加显式类型转换
【发布时间】:2020-03-12 23:24:07
【问题描述】:

无法运行我的查询我的“用户”数据库上有一个“Id”,这是 postgres 的“uuid”类型,我在 dot net core 上有一个 GUID id,我想让你的用户具有相同的 id,并且返回此用户。

    public async Task<T> GetById(Guid entity)
    {
        try
        {
            connection.Open();
            var result = await this.connection.QueryFirstAsync(askForId, entity);
            return result;
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            connection.Close();
        }
    }

实体的值为:

entity: {675d83ca-c7b6-4efe-bf98-46a48e8a28fd}

我的查询是这样的:

private readonly string askForId = "SELECT * FROM Users WHERE Id = @Id";

如何解决这个问题:

 "ClassName": "Npgsql.PostgresException",
    "Message": "External component has thrown an exception.",
    "Data": {
        "Severity": "ERROR",
        "InvariantSeverity": "ERROR",
        "SqlState": "42883",
        "MessageText": "operator does not exist: @ uuid",
        "Hint": "No operator matches the given name and argument type. You might need to add an explicit type cast.",
        "Position": 32,
        "File": "parse_oper.c",
        "Line": "731",
        "Routine": "op_error"
    },
}

【问题讨论】:

  • 不知道任何 C# 或 .net,但看起来您假设 @Id 将是一个占位符,但 Npgsql 可能期望 PostgreSQL 样式的编号占位符(即 $1、@987654327 @, ...)。错误消息表明 PostgreSQL 将 @ 解释为运算符,将 Id 解释为标识符(即 Id 列,它是一个 UUID)。所以阅读 Npgsql 文档,看看你应该使用什么样的占位符。
  • 我不认为这是他的问题@mu_is_too_short。我没有适合他的解决方案,但这是我正在使用的核心 3.x Npgsql 查询"SELECT DG.id, DG.name FROM DEVICE_GROUP DG WHERE DG.id = @id";,它工作正常。调用 new NpgsqlCommand() 后,我使用 cmd.Parameters.AddWithValue("id", id) 我自己放弃了他同样的 UUID 问题并转换为字符串(我不需要性能)所以我无法回答这个问题。
  • @SeñorCMasMas-ReinstateMonica 我猜对了一半;)

标签: c# postgresql .net-core


【解决方案1】:

我将我的查询仅将@Id 更改为@id:

private readonly string askForId = "SELECT * FROM Users WHERE Id = @id";

并更改为 QueryFirstAsyncQueryFirstOrDefaultAsync 因为我需要知道是否找不到任何东西。

public async Task<T> GetById(Guid entity)
        {
            try
            {
                connection.Open();
                var result = await this.connection.QueryFirstOrDefaultAsync<T>(askForId, new { id = entity});
                return result;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                connection.Close();
            }
        }

并将entity 更改为新的{ id = entity} 并正常查询

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2021-05-13
    • 1970-01-01
    • 2011-04-13
    • 2021-02-05
    • 1970-01-01
    • 2016-01-18
    • 2020-08-26
    相关资源
    最近更新 更多