Skip to content

Mapping enum collections #52

@VFSwiss

Description

@VFSwiss

Hi.

Is it possible to map to an array of enums?
I took the Value types collection example, #21, but it doesn't work if you change the type from int to an enum and I can't see a way of getting it to work, I tried using ITypeConverter but by the time CanConvert is called the type if already a list (not int or enum) and the values are all zero.

Am I missing something?
Is there a workaround?

Thanks, Vincent

(sorry about the formatting but the code markup didn't work)

public class OrderTypeConverter : Slapper.AutoMapper.Configuration.ITypeConverter
{
public int Order => 1;

public bool CanConvert(object value, Type type)
{
var conversionType = Nullable.GetUnderlyingType(type) ?? type;
return conversionType == typeof(IList);
}

public object Convert(object value, Type type)
{
var list = value as IEnumerable;
return list?.Cast().ToList();
}
}
public enum OrderType
{
NotSet = 0,
Online = 3,
Phone = 5
}

public class Customer
{
public int CustomerId;
public IList OrdersIds;
}

[Test]
public void I_Can_Map_Value_Typed_Collection()
{
Slapper.AutoMapper.Configuration.TypeConverters.Add(new OrderTypeConverter());

// Arrange
var dictionary = new Dictionary<string, object>
{
{ "CustomerId", 1 },
{ "OrdersIds_$", 3 },
};

var dictionary2 = new Dictionary<string, object>
{
{ "CustomerId", 1 },
{ "OrdersIds_$", 5 }
};

var list = new List<IDictionary<string, object>> { dictionary, dictionary2 };

// Act
var customers = Slapper.AutoMapper.Map(list);

// There should only be a single customer
Assert.That(customers.Count() == 1);

// There should be two values in OrdersIds, with the correct values
Assert.That(customers.FirstOrDefault().OrdersIds.Count == 2);
Assert.That(customers.FirstOrDefault().OrdersIds[0] == OrderType.Online);
Assert.That(customers.FirstOrDefault().OrdersIds[1] == OrderType.Phone);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions