You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET写入PostgreSQL时System.String转MacAddr报错求助

解决Npgsql写入MAC地址字符串报错的问题

你遇到的错误是因为Npgsql的MacAddr8处理程序不直接支持字符串类型——虽然你指定了NpgsqlDbType.MacAddr8,但参数值还是字符串,两者类型不匹配导致报错。解决核心是把MAC字符串转换成Npgsql能识别的对应CLR类型,以下是两种常用方案:

方案1:使用PhysicalAddress类型(推荐)

.NET自带的PhysicalAddress是MAC地址的标准CLR类型,Npgsql默认会把它映射到PostgreSQL的macaddr8类型。只需把字符串MAC地址转换为该类型即可:

// 先将MAC字符串转为PhysicalAddress(确保格式为标准格式,比如"00:11:22:33:44:55:66:77")
PhysicalAddress macAddr = PhysicalAddress.Parse(param2);

NpgsqlBatchCommand command = new NpgsqlBatchCommand("INSERT INTO table (param1,param2,param3) VALUES ($1,$2,$3)")
{
    Parameters =
    {
        new() { Value = param1 },
        new() { Value = macAddr, NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.MacAddr8 },
        new() { Value = param3 }
    }
};

如果你的MAC字符串格式不是标准冒号分隔(比如用连字符-),可以先替换格式再解析:

string formattedMac = param2.Replace("-", ":");
PhysicalAddress macAddr = PhysicalAddress.Parse(formattedMac);

方案2:使用Npgsql专属的NpgsqlMacAddr8类型

Npgsql提供了专门的NpgsqlMacAddr8类型来对应PostgreSQL的macaddr8,用法类似:

// 先引用NpgsqlTypes命名空间
using NpgsqlTypes;

NpgsqlMacAddr8 macAddr8 = NpgsqlMacAddr8.Parse(param2);

NpgsqlBatchCommand command = new NpgsqlBatchCommand("INSERT INTO table (param1,param2,param3) VALUES ($1,$2,$3)")
{
    Parameters =
    {
        new() { Value = param1 },
        new() { Value = macAddr8, NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.MacAddr8 },
        new() { Value = param3 }
    }
};

两种方案都能解决类型不匹配的问题,推荐方案1,因为PhysicalAddress是.NET原生类型,通用性更强。

内容的提问来源于stack exchange,提问作者k1dlero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:50:28