Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Conditional mapping in Automapper

Tags:

c#

automapper

I need a little help with some mappings I am doing.

I am mapping a Model which has two fields

public ProductCategory
public string FirstType
public string SecondType

to another Model which has only one field

public string ProductType

Now I have to map the First or Second Type to ProductType based on a the content of ProductCategory.And if the condition is not met the ProductType should be null

For example I need something like this:

.ForMember(dest => dest.ProductType, opt => opt.MapFrom(src => 
{
   if (src.ProductCategory.Equals("something")
     { 
        src.FirstType
     }
   else if (src.ProductCategory.Equals("something")
     {
        src.SecondType
     }
   else 
    {
       null 
    }
}))

Of course the syntax is completely wrong and obviously won`t work , I just wanted to explain what I am trying to achieve.

I have a temporary solution

.ForMember(dest => dest.ProductType, opt => opt.MapFrom(src => src.ProductCategory.Contains("something") ? src.FirstType: src.SecondType))

but it is not completely what I need.

Any suggestions?

Thanks in advance

like image 379
Kristiyan Kyosev Avatar asked May 01 '26 07:05

Kristiyan Kyosev


1 Answers

What you can do to avoid making the map code look very tangled is to actually separate it into methods that you actually know require some checking for the right value to be assigned.

Here's the code

.ForMember(dest => dest.ProductType, opt => opt.MapFrom(src => CalculateProductCategory(src.ProductCategory))) and then you write your own CalculateProductCategory

And your method would look something like this

    public ProductType CalculateProductCategory(ProductCategory category) {

    if (productCategory.Equals("something")
    { 
        return FirstType
    }
    else if (productCategory.Equals("something")
    {
        return SecondType
    }
    else 
    {
       return null 
    }

}
like image 84
fasaas Avatar answered May 02 '26 19:05

fasaas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!