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

Dapper映射问题:存储过程结果无法正确映射到类属性

Dapper中[Column]特性映射存储过程结果失效的解决方法

问题根源

Dapper默认不识别System.ComponentModel.DataAnnotations命名空间下的[Column]特性,你当前使用的正是该特性,所以无法完成数据库列与类属性的映射匹配。

无需修改属性名的解决方案

方法1:改用Dapper.Contrib专属[Column]特性

Dapper的官方扩展库Dapper.Contrib提供了专门用于字段映射的[Column]特性,步骤如下:

  1. 安装NuGet包:Dapper.Contrib
  2. 替换类中的特性引用,使用Dapper.Contrib.Extensions.ColumnAttribute:
using Dapper.Contrib.Extensions;

public class HotelBedFactResponse
{
    [Column("HotelBedFactId")]
    public int Id { get; set; }

    [Column("FactId")]
    public int FactId { get; set; }

    [Column("HotelBedFactCode")]
    public string Code { get; set; }

    [Column("HotelBedFactGroupCode")]
    public string GroupCode { get; set; }

    [Column("HotelBedDescription")]
    public string Description { get; set; }
}
  1. 保持原存储过程调用代码不变,Dapper会自动识别该特性完成映射。

方法2:手动注册自定义映射规则

如果不想引入额外依赖,可以通过Dapper的SqlMapper.SetTypeMap方法,手动让Dapper识别你原有的[Column]特性:
在应用启动初始化阶段(如Program.cs、Startup.cs)添加以下代码:

using Dapper;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

// 为HotelBedFactResponse注册映射规则
SqlMapper.SetTypeMap(typeof(HotelBedFactResponse), new CustomPropertyTypeMap(
    typeof(HotelBedFactResponse),
    (type, columnName) => type.GetProperties().FirstOrDefault(prop =>
        prop.GetCustomAttributes(false)
            .OfType<ColumnAttribute>()
            .Any(attr => attr.Name == columnName)
    )
));

执行后,Dapper在映射时会读取你原来标记的[Column]特性来匹配列名。

方法3:查询时手动转换匿名类结果

如果仅针对当前查询场景,可先将存储过程返回结果映射到匿名类,再手动转换为目标类:

var rawResult = await connection.QueryFirstOrDefaultAsync(query, parameters, commandType: CommandType.StoredProcedure);
if (rawResult == null) return null;

var result = new HotelBedFactResponse
{
    Id = rawResult.HotelBedFactId,
    FactId = rawResult.FactId,
    Code = rawResult.HotelBedFactCode,
    GroupCode = rawResult.HotelBedFactGroupCode,
    Description = rawResult.HotelBedDescription
};

return result;

这种方式无需修改类结构或添加额外配置,适合临时场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:30:11