Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动映射来自不同属性的条件映射_C#_.net_Automapper - Fatal编程技术网

C# 自动映射来自不同属性的条件映射

C# 自动映射来自不同属性的条件映射,c#,.net,automapper,C#,.net,Automapper,我使用Automapper在两个类之间映射属性。但是,我很难从任何一个子属性进行映射。我遵循AutoMapper的定义 我想映射一个手机号码,如果不为空,则映射一个联系人号码;如果有值,则映射二个联系人号码。 但是,第二个映射始终有效,并将其设置为null public class Destination { public string Email { get; set; } public string Mobile { get; set; } public s

我使用Automapper在两个类之间映射属性。但是,我很难从任何一个子属性进行映射。我遵循AutoMapper的定义

我想映射一个手机号码,如果不为空,则映射一个联系人号码;如果有值,则映射二个联系人号码。 但是,第二个映射始终有效,并将其设置为null

public class Destination
{
    
    public string Email { get; set; }
    public string Mobile { get; set; }
    public string Name { get; set; }
}

public class Source
{
    
    public string Email { get; set; }
    public Contact ContactOne { get; set; }
    public Contact ContactTwo { get; set; }
    public string Name { get; set; }
}

public class Contact
{
    public string Mobile { get; set; }
}
映射配置文件

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Destination, Source>()
            .ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.Email))
            //ContactOne DETAILS
            .ForMember(dest => dest.Mobile, opt =>
            {
                opt.PreCondition(src => src.ContactOne != null);
                opt.MapFrom(src => src.ContactOne.Mobile);
            })   
            //ContactTwo DETAILS
            .ForMember(dest => dest.Mobile, opt =>
            {
                opt.PreCondition(src => src.ContactTwo != null);
                opt.MapFrom(src => src.ContactTwo.Mobile);
            });
    }
}
公共类映射配置文件:配置文件
{
公共映射配置文件()
{
CreateMap()
.ForMember(dest=>dest.Email,opt=>opt.MapFrom(src=>src.Email))
//ContactOne详细信息
.ForMember(dest=>dest.Mobile,opt=>
{
opt.predition(src=>src.ContactOne!=null);
opt.MapFrom(src=>src.ContactOne.Mobile);
})   
//两个细节
.ForMember(dest=>dest.Mobile,opt=>
{
opt.predition(src=>src.ContactTwo!=null);
opt.MapFrom(src=>src.ContactTwo.Mobile);
});
}
}
映射

var source = new Source{ Email = "foo@bab.com", ContactOne = new Contact{Mobile = "6487333332"}, ContactTwo = null }
 var data = mapper.Map<Destination, Source>(source);
 // data.Mobile is null
var source=newsource{Email=”foo@bab.com,ContactOne=new Contact{Mobile=“6487333332”},ContactTwo=null}
var data=mapper.Map(源);
//数据。手机为空

有没有办法在AutoMapper中有条件地映射字段?到目前为止,它运行ContactTwo的映射,尽管它为空,并覆盖从ContactOne映射的现有值

@LucianBargaoanu感谢它为我工作!