首页 > 解决方案 > 没有运算符与给定名称和参数类型匹配。您可能需要添加显式类型转换

问题描述

无法运行我的查询我的“用户”数据库上有一个“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#postgresql.net-core

解决方案


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

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

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

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}并正常工作


推荐阅读