我的 DTO 需要 DateTime
属性,但我的 POCO 使用可为空的日期时间。避免必须创建 ForMember
具有此条件的每个属性的映射我创建了一个 ITypeConverter<DateTime?, DateTime>
.我遇到的问题是,当 DTO 和 POCO 都有可为空的 DateTimes 时,会调用此转换器。 DestinationType
是 DateTime
即使该属性是可为空的日期时间。知道如何让这个转换器只在实际可为空的日期时间运行吗?
public class FooDTO
{
public DateTime? FooDate { get; set; }
}
public class FooPoco
{
public DateTime? FooDate { get; set; }
}
class Program
{
static void Main(string[] args)
{
Mapper.CreateMap<FooDTO, FooPoco>();
Mapper.CreateMap<DateTime?, DateTime>()
.ConvertUsing<NullableDateTimeConverter>();
var poco = new FooPoco();
Mapper.Map(new FooDTO() { FooDate = null }, poco);
if (poco.FooDate.HasValue)
Console.WriteLine(
"This should be null : {0}",
poco.FooDate.Value.ToString()); //Value is always set
else
Console.WriteLine("Mapping worked");
}
}
public class NullableDateTimeConverter : ITypeConverter<DateTime?, DateTime>
{
// Since both are nullable date times and this handles converting
// nullable to datetime I would not expect this to be called.
public DateTime Convert(ResolutionContext context)
{
var sourceDate = context.SourceValue as DateTime?;
if (sourceDate.HasValue)
return sourceDate.Value;
else
return default(DateTime);
}
}
我找到了这个帖子 AutoMapper TypeConverter mapping nullable type to not-nullable type但这没什么帮助。
最佳答案
不看我怀疑它在调用你 TypeCoverter
因为它是被转换类型的最佳匹配。
如果您创建另一个 TypeConverter
使用正确的类型,它应该可以正常工作。例如:
public class DateTimeConverter : ITypeConverter<DateTime?, DateTime>
{
public DateTime Convert(ResolutionContext context)
{
var sourceDate = context.SourceValue as DateTime?;
if (sourceDate.HasValue)
return sourceDate.Value;
else
return default(DateTime);
}
}
public class NullableDateTimeConverter : ITypeConverter<DateTime?, DateTime?>
{
public DateTime? Convert(ResolutionContext context)
{
var sourceDate = context.SourceValue as DateTime?;
if (sourceDate.HasValue)
return sourceDate.Value;
else
return default(DateTime?);
}
}
请注意,如果您希望这些可以进一步简化为
public class DateTimeConverter : TypeConverter<DateTime?, DateTime>
{
protected override DateTime ConvertCore(DateTime? source)
{
if (source.HasValue)
return source.Value;
else
return default(DateTime);
}
}
public class NullableDateTimeConverter : TypeConverter<DateTime?, DateTime?>
{
protected override DateTime? ConvertCore(DateTime? source)
{
return source;
}
}
然后只需初始化两个转换器:
Mapper.CreateMap<DateTime?, DateTime>().ConvertUsing<DateTimeConverter>();
Mapper.CreateMap<DateTime?, DateTime?>().ConvertUsing<NullableDateTimeConverter>();
Mapper.AssertConfigurationIsValid();
关于datetime - 可为空的日期时间到日期时间转换器自动映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16340802/