I'm trying to map an entity to a enum. As I was searching for a source I found this:
using Should;
public enum OrderStatus : short
{
InProgress = 0,
Complete = 1
}
public enum OrderStatusDto
{
InProgress = 0,
Complete = 1
}
[Test]
public void Example()
{
Mapper.Map<OrderStatus, OrderStatusDto>(OrderStatus.InProgress)
.ShouldEqual(OrderStatusDto.InProgress);
Mapper.Map<OrderStatus, short>(OrderStatus.Complete).ShouldEqual((short)1);
Mapper.Map<OrderStatus, string>(OrderStatus.Complete).ShouldEqual("Complete");
Mapper.Map<short, OrderStatus>(1).ShouldEqual(OrderStatus.Complete);
Mapper.Map<string, OrderStatus>("Complete").ShouldEqual(OrderStatus.Complete);
}
but I think this works for only enum-to-enum mapping. because when I try to use .ShouldEqual, intellisense can't find it. In that codeblock, there is a reference that's called Should but I couldn't find its reference anywhere.
Any ideas about how to use automapper to map between enum and entity/class? Any ideas about using Should?
@I updated the question because without seeing the actual code, it's harder to consider a solution. Here is the code snippet that might be needed:
public class ParameterEnum
{
/// <summary>
/// Enum Sayisi: 2650, Son Guncelleme Tarihi: 21.2.2013 09:40:37
/// </summary>
public enum Parameters : int
{
...
IsEmriTuruIsTalebi = 138,
<summary>
Adi: Kalite Öneri; ID: 2218; Seviyesi: 3; Aciklamasi: ; Aktif Mi: True
</summary>
...}}
and this is where normal mapping done:
isEmriEntity.IsEmriTuruId = (int)ParameterEnum.Parameters.IsEmriTuruIsTalebi;
You should look into ITypeConverter. Something like this should do the job:
Mapper.CreateMap<OrderStatus, OrderStatusDto>().ConvertUsing(new OrderStatusConverter());
and your converter would look like so:
public class OrderStatusConverter: ITypeConverter<OrderStatus, OrderStatusDto>
{
public OrderStatusDto Convert(OrderStatus source)
{
return (OrderStatusDto)source;
}
}
That should be enough to apply the same approach to any other cross-type mappings in your DTOs.
EDIT:
On your enum conversion error, using this as an example for clarity (an enum is not a DTO):
public enum ExampleEnum : short
{
SomeValue,
SomeOtherValue,
BigValue = 100,
}
public enum AnotherEnum
{
Foo,
Bar,
}
This should make the enum conversion clearer (don't cast to int at all).
private void Test()
{
// Casting to int only works when the value is 0
// This works (SomeValue = 0)
AnotherEnum example = (int) ExampleEnum.SomeValue;
// This won't even compile (SomeOtherValue = 1)
AnotherEnum example2 = (int) ExampleEnum.SomeOtherValue;
// Casting to another enum works fine
AnotherEnum example2 = (AnotherEnum) ExampleEnum.SomeOtherValue;
// Just be careful of values that don't exist in the target enum
// This will compile even though it won't work at run-time (BigValue = 100)
AnotherEnum example2 = (AnotherEnum) ExampleEnum.BigValue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With