我有一个这样的 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; }
}
}
和内部模型类到自动映射器,如下所示:
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.AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Mapping types:
DateTimeOffset -> DateTime
System.DateTimeOffset -> System.DateTime
Destination Member:
SinceDate
任何人都可以帮我定义一个正确的映射配置来解决它吗?
非常感谢。
我用一个值转换器做到了。它对我有用:
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
}
您可以使用 ITypeConverter
在进行映射时只需使用 DateTimeOffset 变量的 DateTime 属性:
.ForPath(d => d.DateTime, opt => opt.MapFrom(s => s.DateTimeOffset.DateTime));
@jrn6270 的答案似乎将 DateTimeOffset 映射到 DateTime 类型:
.ForPath(d => d.DateTime, opt => opt.MapFrom(s => s.DateTimeOffset.DateTime));
但是,它不会将正确的日期复制到其他属性......
为了实现从DateTimeOffset到DateTime的正确映射。添加新的:
private static DateTime DateTimeOffsetToDateTime(DateTimeOffset source)
{
string dateTimeString = source.ToString();
return DateTimeOffset.Parse(dateTimeString).UtcDateTime;
}
然后在你的映射器中添加:
.ForPath(d => d.SomeDateTimeProperty, opt => opt.MapFrom(s => DateTimeOffsetToDateTime(s.SomeDateTimeProperty)))