1.使用Nuget 搜尋套件AutoMapper並安裝
2. namespace 加入 using AutoMapper;
3.以下為基本使用方式
var query = db.vw_SchoolStdTotal.ToList(); var config = new MapperConfiguration(cfg => cfg.CreateMap<vw_SchoolStdTotal, SchoolStdTotalDataModel>()); config.AssertConfigurationIsValid(); var mapper = config.CreateMapper(); result = mapper.Map<List<vw_SchoolStdTotal>, List<SchoolStdTotalDataModel>>(query);
var config = new MapperConfiguration( cfg => cfg.CreateMap<SchoolStdTotalDataModel, vw_SchoolStdTotalViewModel>() //忽略此欄對應 .ForMember(d => d.SchoolName, o => o.Ignore()) .ForMember(d => d.ProfessionGroupDetailName, o => o.MapFrom(s => s.ProfessionGroupDetailName == null ? "國中部" : s.ProfessionGroupDetailName)) //資料源使用function處理 .ForMember(d => d.Button, o => o.MapFrom(s => dataListButton.ForGetTotalNumberHighSchoolList(desFun.DESEncrypt(s.ID.ToString())))));更新資料寫法
不需要的欄位使用Ignore排除,關聯Key也要排除不然會出錯
var query = db.PersonalInfo.Where(f => f.ID == ID).FirstOrDefault(); if (query != null) { var config = new MapperConfiguration( cfg => cfg.CreateMap未完待續.......() .ForMember(d => d.x1, o => o.Ignore()) .ForMember(d => d.x2, o => o.Ignore()) .ForMember(d => d.ModifyDate, o => o.MapFrom(s => DateTime.Now))); config.AssertConfigurationIsValid(); var mapper = config.CreateMapper(); //PersonalInfo personalInfo = db.PersonalInfo.Find(21); mapper.Map(viewModel, query); db.SaveChanges(); }
參考來源
https://automapper.org/
沒有留言:
張貼留言