本文介绍了有条件地将一种源类型映射到两种目标类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的源DTO

public class Member 
{
    public string MemberId {get;set;}
    public string MemberType {get;set;}
    public string Name {get;set;}
}

成员类型可以是人"或公司".

The member type can be "Person" or "Company".

还有两个这样的目标类

public class PersonMember 
{
    public int PersonMemberId {get;set;}
    public string Name {get;set;}
}

public class CompanyMember 
{
    public int CompanyMemberId {get;set;}
    public string Name {get;set;}
}

我想使用Automapper检查源类中MemberType的值,并根据该类型将其映射到两种目标类型之一.

I want to use Automapper to check what the value of MemberType is in the source class and depending on that type, map to one of the two destination types.

我看到了有条件地映射的示例,但是它映射了它的字段执行条件检查.我想检查条件并映射其他字段.

I saw the example of conditionally mapping, but it maps the field it performs the conditional check on. I want to check the condition and map a different field.

var config = new MapperConfiguration(cfg => {
  cfg.CreateMap<Foo,Bar>()
    .ForMember(dest => dest.baz, opt => opt.Condition(src => (src.baz >= 0))); 
});

我的目标就是这样-

cfg.CreateMap<Member, PersonMember>()
.ForMember(dest => PersonMember.PersonMemberId, opt => if the source.MemberType == "Person" perform mapping from MemberId, otherwise do nothing);

cfg.CreateMap<Member, CompanyMember>()
.ForMember(dest => CompanyMember.CompanyMemberId, opt => if the source.MemberType == "Company" perform mapping from MemberId, otherwise do nothing);

推荐答案

使用自动映射器,必须在调用映射器上指定返回类型,例如. mapper.Map<PersonMember>(member),这表明返回类型为PersonMember,因此您无法返回CompanyMember.

With automapper you must specify return type on invocation mapper eg. mapper.Map<PersonMember>(member), this tells that return type is PersonMember so you can't return CompanyMember.

您可以执行以下操作:

var configPerson = new MapperConfiguration(cfg => cfg.CreateMap<Member, PersonMember>());
var configCompany = new MapperConfiguration(cfg => cfg.CreateMap<Member, CompanyMember>());

PersonMember personMember = null;
CompanyMember companyMember = null;

switch (member.MemberType )
{
    case "PersonMember":
        var mapper = configPerson.CreateMapper();
        personMember = mapper.Map<PersonMember>(member);
        break;
    case "CompanyMember":
        var mapper = configCompany.CreateMapper();
        companyMember = mapper.Map<CompanyMember>(member);
        break;
    default:
        throw new Exception("Unknown type");
        break;
}

或者您可以尝试将自定义类型转换器object一起使用作为返回类型.

Or you can try Custom type converters with object as return type.

这篇关于有条件地将一种源类型映射到两种目标类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:00