gpt4 book ai didi

c# - Npgsql v3 上的 Dapper IPAddress/PhysicalAddress/Enum 参数支持

转载 作者:行者123 更新时间:2023-11-30 15:24:55 31 4
gpt4 key购买 nike

Npgsql支持从类型为macaddr System.Net.NetworkInformation.PhysicalAddress和 System.Net.IPAddress >inet,分别。例如,可以使用带有 Dapper 的 Npgsql 填充以下类:

-- Postgres CREATE TABLE command
CREATE TABLE foo (
ipaddress inet,
macaddress macaddr
);
// C# class for type "foo"
public class foo
{
public IPAddress ipaddress { get; set; }
public PhysicalAddress macaddress { get; set; }
}

// Code that loads all data from table "foo"
IDbConnection connection = new NpgsqlConnection(connectionString);
var foos = connection.Query<foo>("SELECT * FROM foo");

由于 Npgsql v3.0.1 以二进制形式发送数据,我假设这意味着类型 inetmacaddr 有一些二进制表示。但是,当我使用上面的相同声明运行以下代码时...

// Code that tries to load a specific row from "foo"
var query = "SELECT * FROM foo WHERE macaddress = :macAddress";
var queryParams = new DynamicParameters();
queryParams.Add("macAddress", PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"));
IDbConnection connection = new NpgsqlConnection(connectionString);
var foos = connection.Query<foo>(query, queryParams);

我得到异常:

Problem with query: SELECT * FROM foo WHERE macaddress = :macAddress
System.NotSupportedException : The member macAddress of type System.Net.NetworkInformation.PhysicalAddress cannot be used as a parameter value

Dapper/Npgsql 是如何知道如何从 inetmacaddr 类型的列中解析 IPAddressPhysicalAddress ,但我无法将这些类型用作参数?在以前版本的 Npgsql 中,我只是将 ToString() 结果作为参数值发送,但是在 Npgsql v3.0.1 中,以下代码...

// Code that tries to load a specific row from "foo"
// The only change from above is the "ToString()" method called on PhysicalAddress
var query = "SELECT * FROM foo WHERE macaddress = :macAddress";
var queryParams = new DynamicParameters();
queryParams.Add("macAddress", PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF").ToString());
IDbConnection connection = new NpgsqlConnection(connectionString);
var foos = connection.Query<foo>(query, queryParams);

生成异常:

Problem with query: SELECT * FROM foo WHERE macaddress = :macAddress
Npgsql.NpgsqlException : 42883: operator does not exist: macaddr = text

我知道我可以将查询更改为“SELECT * FROM foo WHERE macaddress = :macAddress::macaddr”,但我想知道是否有更简洁的方法来解决这个问题?有没有计划在不久的将来增加对这些类型的支持?

-- 开始编辑--

我刚刚意识到同样的问题困扰着枚举类型。如果我有一个枚举参数,我可以从查询结果中解析它,但无法将枚举传递给 Postgres。例如:

CREATE TYPE bar AS ENUM (
val1,
val2
);

CREATE TABLE log (
mybar bar
);
public enum bar
{
val1,
val2
}

public class log
{
public bar mybar { get; set; }
}

// Code that loads all data from table "log"
NpgsqlConnection.RegisterEnumGlobally<bar>();
IDbConnection connection = new NpgsqlConnection(connectionString);
var logs = connection.Query<log>("SELECT * FROM log");

// Code that attempts to get rows from log with a specific enum
var query = "SELECT * FROM log WHERE mybar = :barParam";
var queryParams = new DynamicParameters();
queryParams.Add("barParam", bar.val1);
// The following throws an exception
logs = connection.Query<log>(query, queryParams);

在上面,一切正常,直到抛出以下异常的最后一行:

42883: operator does not exist: bar = integer

如果相反,我将查询更改为:

SELECT * FROM log WHERE mybar = :barParam::bar

然后我得到异常:

42846: cannot cast type integer to bar

我可以获得枚举值作为参数传递的唯一方法是将它们作为文本传递并在查询中转换参数,如下所示:

// Code that successfully performs the query
var query = "SELECT * FROM log WHERE mybar = :barParam::bar";
var queryParams = new DynamicParameters();
queryParams.Add("barParam", bar.val1.ToString());
logs = connection.Query<log>(query, queryParams);

当然有更好的方法来解决这个问题。任何人都可以阐明那是什么吗?

最佳答案

感谢 Hambone 和 Shay 的帮助,我找到了解决此问题的方法 IPAddressPhysicalAddress类型。问题是 inetmacaddr是特定于 Postgres 的,而 Dapper 似乎与提供者无关。因此,解决方案是添加一个自定义处理程序,在将这些参数类型转发到 Npgsql 之前设置适当的 NpgsqlDbType。自定义处理程序可以编码为:

using System;
using System.Data;
using Dapper;
using Npgsql;
using NpgsqlTypes;

namespace MyNamespace
{
internal class PassThroughHandler<T> : SqlMapper.TypeHandler<T>
{

#region Fields

/// <summary>Npgsql database type being handled</summary>
private readonly NpgsqlDbType _dbType;

#endregion

#region Constructors

/// <summary>Constructor</summary>
/// <param name="dbType">Npgsql database type being handled</param>
public PassThroughHandler(NpgsqlDbType dbType)
{
_dbType = dbType;
}

#endregion

#region Methods

public override void SetValue(IDbDataParameter parameter, T value)
{
parameter.Value = value;
parameter.DbType = DbType.Object;
var npgsqlParam = parameter as NpgsqlParameter;
if (npgsqlParam != null)
{
npgsqlParam.NpgsqlDbType = _dbType;
}
}

public override T Parse(object value)
{
if (value == null || value == DBNull.Value)
{
return default(T);
}
if (!(value is T))
{
throw new ArgumentException(string.Format(
"Unable to convert {0} to {1}",
value.GetType().FullName, typeof(T).FullName), "value");
}
var result = (T)value;
return result;
}

#endregion

}
}

然后,在我的数据访问层 (DAL) 类的静态构造函数中,我只需添加以下行:

var ipAddressHandler  =
new PassThroughHandler<IPAddress>(NpgsqlDbType.Inet);
var macAddressHandler =
new PassThroughHandler<PhysicalAddress>(NpgsqlDbType.MacAddr);
SqlMapper.AddTypeHandler(ipAddressHandler);
SqlMapper.AddTypeHandler(macAddressHandler);

现在我可以发送 PhysicalAddressIPAddress通过 Dapper 传递参数,无需将它们字符串化。

然而,枚举带来了另一个挑战,因为 Dapper 1.42 不支持添加自定义枚举处理程序(参见 Dapper 问题 #259/#286 )。更不幸的是,Dapper 默认情况下将枚举值作为整数发送到底层实现。因此,目前无法在使用 Dapper 1.42(或更早版本)时将枚举值发送到 Npgsql 而不将它们转换为字符串。我已经就此问题联系了 Marc Gravell,并希望在不久的将来得到某种解决方案。在那之前,决议是:

1) Use Npgsql directly, bypassing Dapper
2) Send all enum values as text, and cast to the appropriate type in the query

我个人选择继续选项 #2。


开始编辑

在查看 Dapper 源代码后,我意识到还有第三种选择可以实现此目的。虽然不可能为每个枚举类型创建自定义处理程序,但可以将枚举值包装在 SqlMapper.ICustomQueryParameter 中。目的。由于代码只需要将枚举值传递给Npgsql,所以实现很简单:

using System;
using System.Data;
using Dapper;

namespace MyNamespace
{
internal class EnumParameter : SqlMapper.ICustomQueryParameter
{

#region Fields

/// <summary>Enumerated parameter value</summary>
private readonly Enum _val;

#endregion

#region Constructors

/// <summary>Constructor</summary>
/// <param name="val">Enumerated parameter value</param>
public EnumParameter(Enum val)
{
_val = val;
}

#endregion

#region Methods

public void AddParameter(IDbCommand command, string name)
{
var param = command.CreateParameter();
param.ParameterName = name;
param.DbType = DbType.Object;
param.Value = _val;
command.Parameters.Add(param);
}

#endregion

}
}

我的代码已经设置好,每个参数都添加到 Dictionary<string, object> 中, 然后转换为 DynamicParameters单个代码路径中的对象。因此,我能够将以下检查添加到从一个转换为另一个的循环中:

var queryParams = new DynamicParameters();
foreach (var kvp in paramDict)
{
var enumParam = kvp.Value as Enum;
if (enumParam == null)
{
queryParams.Add(kvp.key, kvp.Value);
}
else
{
queryParams.Add(kvp.key, new EnumParameter(enumParam));
}
}

通过这样做,枚举值被传递给 Npgsql 而没有被转换为它们的等效数字(因此,没有丢失相关的类型信息)。整个过程看起来仍然非常复杂,但至少有一种方法可以使用 Npgsql v3 二进制形式通过 Dapper 传递枚举值参数

关于c# - Npgsql v3 上的 Dapper IPAddress/PhysicalAddress/Enum 参数支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32105274/

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