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

Dapper.Contrib操作PostgreSQL报字段不存在错误如何解决?

解决方案

方案1:全局配置命名转换规则(最便捷)

Dapper.Contrib 提供了全局映射委托,可以统一将C#帕斯卡命名的属性名转换为PostgreSQL常用的小写命名,在程序启动时执行一次配置即可,不需要修改现有模型代码:

using Dapper.Contrib.Extensions;

// 全局配置列名映射:属性名转全小写
SqlMapperExtensions.ColumnNameMapper = property => property.Name.ToLower();
// 若表名也需要统一转换,可以同步配置表名映射
SqlMapperExtensions.TableNameMapper = type => type.Name.ToLower() + "s";

配置后生成的SQL会自动把Created转为created,Value转为value,和数据库字段完全匹配。

方案2:自定义映射规则读取[Column]特性

如果你需要保留部分字段的自定义映射逻辑,可以扩展列名映射规则,自动读取属性上标注的[Column]特性值:

using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using Dapper.Contrib.Extensions;

SqlMapperExtensions.ColumnNameMapper = property =>
{
    // 读取属性上的Column特性
    var columnAttr = property.GetCustomAttributes(typeof(ColumnAttribute), false)
        .FirstOrDefault() as ColumnAttribute;
    // 存在Column特性则用配置的名称,否则转全小写
    return columnAttr?.Name ?? property.Name.ToLower();
};

配置后你之前写的[Column("created")]这类配置就会被Dapper.Contrib正常识别。

额外优化建议

你当前使用UUID作为主键且由数据库默认生成,建议给Id属性加上[Key]特性,明确告诉Dapper.Contrib该字段是数据库自动生成的主键,避免插入时出现异常:

[Table("posts")]
public class Post
{
    [Key]
    [Column("id")]
    public Guid Id { get; set; }

    [Column("created")]
    public long Created { get; set; }

    [Column("value")]
    public string Value { get; set; }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:45:02