可为空的datetime到datetime转换器自动映射器

可为空的datetime到datetime转换器自动映射器,datetime,automapper,nullable,Datetime,Automapper,Nullable,我的DTO需要DateTime属性,但我的POCO使用可为空的DateTime。为了避免为具有此条件的每个属性创建FormMember映射,我创建了一个ITypeConverter。我遇到的问题是,当DTO和POCO都具有可为空的日期时间时,调用此转换器。DestinationType是DateTime,即使该属性是可为空的DateTime。你知道我如何让这个转换器只在实际的可为空的日期时间内运行吗 public class FooDTO { 公共日期时间?FooDate{get;set;} }

我的DTO需要
DateTime
属性,但我的POCO使用可为空的DateTime。为了避免为具有此条件的每个属性创建
FormMember
映射,我创建了一个
ITypeConverter
。我遇到的问题是,当DTO和POCO都具有可为空的日期时间时,调用此转换器。
DestinationType
DateTime
,即使该属性是可为空的DateTime。你知道我如何让这个转换器只在实际的可为空的日期时间内运行吗

public class FooDTO
{
公共日期时间?FooDate{get;set;}
}
公共级FooPoco
{
公共日期时间?FooDate{get;set;}
}
班级计划
{
静态void Main(字符串[]参数)
{
CreateMap();
Mapper.CreateMap()
.ConvertUsing();
var poco=新的FooPoco();
Map(newfoodto(){FooDate=null},poco);
if(poco.FooDate.HasValue)
控制台写入线(
“这应该为空:{0}”,
poco.FooDate.Value.ToString());//始终设置值
其他的
Console.WriteLine(“映射已工作”);
}
}
公共类NullableDateTimeConverter:ITypeConverter
{
//因为两者都是可为空的日期时间,并且这将处理转换
//可以为null的datetime我不希望调用它。
公共日期时间转换(ResolutionContext上下文)
{
var sourceDate=context.SourceValue作为DateTime?;
if(sourceDate.HasValue)
返回sourceDate.Value;
其他的
返回默认值(日期时间);
}
}

我找到了这篇文章,但帮不了什么忙

不看,我怀疑它调用了您的
typeconverter
,因为它是转换类型的最佳匹配

如果您使用正确的类型创建另一个
TypeConverter
,它应该可以正常工作。例如:

公共类DateTimeConverter:ITypeConverter
{
公共日期时间转换(ResolutionContext上下文)
{
var sourceDate=context.SourceValue作为DateTime?;
if(sourceDate.HasValue)
返回sourceDate.Value;
其他的
返回默认值(日期时间);
}
}
公共类NullableDateTimeConverter:ITypeConverter
{
公共日期时间?转换(ResolutionContext上下文)
{
var sourceDate=context.SourceValue作为DateTime?;
if(sourceDate.HasValue)
返回sourceDate.Value;
其他的
返回默认值(日期时间?);
}
}
请注意,如果您希望,这些可以进一步简化为

公共类DateTimeConverter:TypeConverter
{
受保护的覆盖日期时间转换器核心(日期时间?源)
{
if(source.HasValue)
返回source.Value;
其他的
返回默认值(日期时间);
}
}
公共类NullableDateTimeConverter:TypeConverter
{
受保护的覆盖DateTime?ConvertCore(DateTime?源)
{
返回源;
}
}
然后只需初始化两个转换器:

Mapper.CreateMap().ConvertUsing();
CreateMap().ConvertUsing();
assertConfigurationsValid();

如果需要,您应该能够进一步简化它,并将
NullableDateTimeConverter
内联到
CreateMap
。没什么可赚的,所以我不费心,但可能会让它看起来不那么霍奇:)