C# - AutoMapper之不同類型的轉換


 

一、Dto & Model約定

    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; }
    }

 

 

 二、需求:篩選出TestModel中StartTime小於當前時間的候選人,並將其傳輸給TestDto的Candidates字段。

class Program
    {
        static void Main(string[] args)
        {
            var testModel = new TestModel()
            {
                Name = "Frankie",
                Age = 22,
                Candidates = new List<CandidateModel>()
                {
                    new CandidateModel(){StartTime = new DateTime(2018, 10, 9, 10, 0, 0), Candidate = "貝貝"},
                    new CandidateModel(){StartTime = new DateTime(2018, 10, 22, 10, 0, 0), Candidate = "asan"},
                    new CandidateModel(){StartTime = new DateTime(2018, 10, 10, 10, 0, 0), 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:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM