简体   繁体   English

Automapper 中的多条件映射

[英]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现在我必须根据 ProductCategory 的内容将第一个或第二个类型映射到 ProductType。如果不满足条件,则 ProductType 应该为 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 
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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