在下面的示例代码中,我得到一个“可空对象必须有一个值”。为什么我需要以下修复来完成这项工作:
.ForMember(dest => dest.ShirtColor,
dest => dest.MapFrom(src => src.ShirtColor != null
? new OptionSetValue((int) src.ShirtColor)
: null))
AutoMapper.Mapper.CreateMap<PersonA, PersonB>()
.ForMember(dest => dest.FirstName, dest => dest.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LastName, dest => dest.MapFrom(src => src.LastName))
// Condition to avoid overwriting existing data!!!
.ForMember(dest => dest.ShirtColor,
dest => dest.Condition(src => src.ShirtColor != null))
.ForMember(dest => dest.ShirtColor,
dest => dest.MapFrom(
src => new OptionSetValue((int)src.ShirtColor)))
// Fix that should not be needed due to condition:
//.ForMember(dest => dest.ShirtColor,
// dest => dest.MapFrom(
// src => src.ShirtColor != null
// ? new OptionSetValue((int) src.ShirtColor)
// : null));
PersonA source = new PersonA();
source.FirstName = "Thomas";
source.LastName = "Jefferson";
source.ShirtColor = null; // nullable int
PersonB destination = new PersonB();
destination.FirstName = "Thomas";
destination.LastName = "Jefferson";
destination.ShirtColor = new OptionSetValue(4);
// Results in: "Nullable object must have a value" despite the fact that
// condition should have been met!
Mapper.Map<PersonA, PersonB>(source, destination);
Debug.Assert(destination.ShirtColor != null);
Console.WriteLine("Our existing data was not overwritten!!");
Console.WriteLine("Hit enter to exit");
Console.ReadLine();
下面是 OptionSet 的定义方式: public class OptionSetValue { public OptionSetValue(){}
public OptionSetValue(int value)
{
Number = value;
}
public int Number { get; set; }
}