以下のコード例では、「Nullable オブジェクトには値が必要です」というメッセージが表示されます。これを機能させるために次の修正が必要なのはなぜですか。
.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; }
}