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

如何配置AutoMapper解决DateTimeOffset与DateTime映射报错问题

AutoMapper映射DateTimeOffset到DateTime失败的解决方法

场景说明

存在两个同名的SubjectAddressDataDto类:

  • 公共DTO类(带Json序列化特性,SinceDate为DateTimeOffset类型,Country为枚举类型)
  • 内部模型类(SinceDate为DateTime类型,Country为字符串类型)

执行AutoMapper映射时,出现类型转换错误:

---> AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping.
  
  Mapping types:
  DateTimeOffset -> DateTime
  System.DateTimeOffset -> System.DateTime
  
  Destination Member:
  SinceDate 

公共DTO类代码

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.0.22.0 (Newtonsoft.Json v11.0.0.0)")]
public partial class SubjectAddressDataDto 
{
    
    [Newtonsoft.Json.JsonProperty("country", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public CountryCodeDto Country { get; set; }

    /// <summary>The addrees data are valid since this date</summary>
    [Newtonsoft.Json.JsonProperty("sinceDate", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
    [Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]
    public System.DateTimeOffset SinceDate { get; set; }

    private System.Collections.Generic.IDictionary<string, object> _additionalProperties = new System.Collections.Generic.Dictionary<string, object>();

    [Newtonsoft.Json.JsonExtensionData]
    public System.Collections.Generic.IDictionary<string, object> AdditionalProperties
    {
        get { return _additionalProperties; }
        set { _additionalProperties = value; }
    }
}

内部模型类代码

public class SubjectAddressDataDto
{
    public string FullAddress { get; set; }
    public string Street { get; set; }
    public string Locality { get; set; }
    public string Region { get; set; }
  
    public string PostalCode { get; set; }
    public string Country { get; set; }

    public DateTime SinceDate { get; set; }
}

解决步骤

需要配置AutoMapper的全局类型转换规则和类间映射规则,处理两个核心转换:DateTimeOffset→DateTime、CountryCodeDto枚举→string。

1. 创建映射Profile

using AutoMapper;

// 替换为实际项目的命名空间
namespace YourMappingNamespace
{
    public class AddressMappingProfile : Profile
    {
        public AddressMappingProfile()
        {
            // 全局配置DateTimeOffset到DateTime的转换
            // 业务场景不同可选择UtcDateTime(UTC时间)或LocalDateTime(本地时间)
            CreateMap<DateTimeOffset, DateTime>()
                .ConvertUsing(input => input.LocalDateTime);

            // 配置两个同名DTO的映射(必须指定完整命名空间区分类型)
            CreateMap<YourPublicNamespace.SubjectAddressDataDto, YourInternalNamespace.SubjectAddressDataDto>()
                // 处理枚举转字符串,若需自定义枚举显示值可替换为对应的逻辑
                .ForMember(dest => dest.Country, opt => opt.MapFrom(src => src.Country.ToString()))
                // 其他同名属性AutoMapper会自动匹配,无需额外配置
                .ReverseMap(); // 如需反向映射可添加此配置
        }
    }
}

2. 注册Profile到AutoMapper

在项目启动时(如ASP.NET Core的Program.cs)注册该映射Profile:

// ASP.NET Core 6+ 示例
builder.Services.AddAutoMapper(typeof(AddressMappingProfile));

关键说明

  • 转换DateTimeOffset到DateTime时,需根据业务场景选择对应时区的时间,避免出现时区偏差问题。
  • 两个类同名,映射时必须指定完整命名空间,否则AutoMapper无法区分目标与源类型。
  • 除Country和SinceDate外,其他同名属性AutoMapper会自动完成映射,无需手动配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:18:49