5

Could someone show an example with mapping bool property to a enum type? I'm worry about null members in destenition. I need to have something like these:

null property value to a first enum value;

0 to a second;

1 to the last;

user3818229
  • 1,537
  • 2
  • 21
  • 46

2 Answers2

7

Unfortutely, as expressed here AutoMapper null source value and custom type converter, fails to map? you can't directly map "null" to something, because a map of null will always return default(T), so you can't do something like this:

    CreateMap<bool?, MyStrangeEnum>()
        .ConvertUsing(boolValue => boolValue == null
            ? MyStrangeEnum.NullValue
            : boolValue.Value ? MyStrangeEnum.True : MyStrangeEnum.False);

If you map an object property, on the other hand, it will work:

public class MapperConfig : Profile
{
    protected override void Configure()
    {
        CreateMap<Foo, Bar>()
            .ForMember(dest => dest.TestValue,
                e => e.MapFrom(source =>
                    source.TestValue == null
                        ? MyStrangeEnum.NullValue
                        : source.TestValue.Value ? MyStrangeEnum.True : MyStrangeEnum.False));
    }
}

public class Foo
{
    public Foo()
    {
        TestValue = true;
    }
    public bool? TestValue { get; set; }
}

public class Bar
{
    public MyStrangeEnum TestValue { get; set; }
}

public enum MyStrangeEnum
{
    NullValue = -1,
    False = 0,
    True = 1
}
Luca Ghersi
  • 3,261
  • 18
  • 32
0

try like the below code :

Enum :

public enum BoolVal {
    NullVal = -1 ,
    FalseVal = 0 ,
    TrueVal = 1
}

Declare Value :

        var val  = BoolVal.NullVal; // OR (BoolVal.FalseVal ,BoolVal.TrueVal)

Test Value :

// This will return => null or true or false 
bool? value1 = (val == BoolVal.NullVal ? null : (bool?)Convert.ToBoolean(val)); 
Osama AbuSitta
  • 3,918
  • 4
  • 35
  • 51