C# - AutoMapper之不同类型的转换
阅读原文时间:2023年07月11日阅读:2
class TestDto  
{  
    public string Name { get; set; }  
    public int Age { get; set; }  
    public List<string> Candidates { get; set; }  
}

class TestModel  
{  
    public string Name { get; set; }  
    public int Age { get; set; }  
    public List<CandidateModel> Candidates { get; set; }  
}  
class CandidateModel  
{  
    public DateTime StartTime { get; set; }  
    public string Candidate { get; set; }  
}

class Program
{
static void Main(string[] args)
{
var testModel = new TestModel()
{
Name = "Frankie",
Age = ,
Candidates = new List()
{
new CandidateModel(){StartTime = new DateTime(, , , , , ), Candidate = "贝贝"},
new CandidateModel(){StartTime = new DateTime(, , , , , ), Candidate = "asan"},
new CandidateModel(){StartTime = new DateTime(, , , , , ), Candidate = "pangzi"}
}
};
// DataTime.Now : {2018/10/21 21:51:12}
testModel.Candidates = testModel.Candidates.Where(_ => _.StartTime < DateTime.Now).ToList();

        Mapper.Initialize(\_ => \_.CreateMap<TestModel, TestDto>()  
            .ForMember(s => s.Candidates,  
                d => d.MapFrom(x => x.Candidates.Select(y => y.Candidate))));

        var testDto = Mapper.Map<TestDto>(testModel);  
    }  
}

Result: