简体   繁体   中英

Multiple Conditional mapping in 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

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 
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM