Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mapping enum collections #52

Open
VFSwiss opened this issue Apr 3, 2017 · 0 comments
Open

Mapping enum collections #52

VFSwiss opened this issue Apr 3, 2017 · 0 comments

Comments

@VFSwiss
Copy link

VFSwiss commented Apr 3, 2017

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);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant