.net 自动Map器从DateTimeOffset到DateTime并反转

amrnrhlw  于 2023-05-23  发布在  .NET
关注(0)|答案(2)|浏览(218)

我有一个这样的publicDto类:

[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; }
        }
    
    
    }

和内部模型类自动Map如下:

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; }
    }
}

在自动Map我收到以下错误:

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

谁能帮我定义一个正确的Map配置来解决这个问题?
多谢了

blpfk2vs

blpfk2vs1#

您可以使用ITypeConverter<TSource,TDestination>接口的实现创建一个自定义类型转换器,并使用ConvertUsing方法将其添加到配置文件类。来自自动Map器的文件:custom type converters

whitzsjs

whitzsjs2#

我用一个值转换器做的。它对我有效:

public class MappingProfile : Profile{
    public MappingProfile()
    {
        CreateMap<Src,DestDto>().ForMember(d => d.SinceDate , o => o.ConvertUsing(new DateTimeTypeConverter()))).ReverseMap();
    }
}
public class DateTimeTypeConverter : IValueConverter<DateTimeOffset?, DateTime?>
{
    public DateTime? Convert(DateTimeOffset? source, ResolutionContext context) => source?.LocalDateTime;
    // enter code here
}

相关问题