AutoMapper is a magical tool in the realm of dotnet, mapping data transfer object into another effortlessly.
熙熙攘攘之街道上,運貨人正忙碌於控制區及服務區之間的貨物,而服務區之工者一刻也不得閒著,忙碌於貨物及驛站之間的來往,或許將貨物送往各各驛站並非困難,然而如此費時費力之法亦非明智之舉,是故工者於是乎誕生了以省時知名之魔法,名作AutoMapper。
AutoMapper乃類別對映轉換之套件,可快速且簡單實現類別對映之處理,減少繁瑣之程式碼,其可用以將兩個或多個類別之屬性或字段進行映射,以便將一個類別之資料轉換為另一個類別之資料。若欲使用AutoMapper則需以builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
,並於Program.cs中進行註冊。註冊完後可新增一資料夾,名「Profiles」,此處如魔法書般,可記錄AutoMapper在個別情況下之映射:
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
// InformationDto為映射之來源
// AdventurerProfile為映射之目的
CreateMap<InformationDto, AdventurerProfile>()
.ForMember(profile => profile.Created_At, information => information.MapFrom(o => DateTime.Now))
.ForMember(profile => profile.Sigil, information => information.MapFrom(o => Guid.NewGuid().ToString()));
}
}
AutoMapper設定後,接著將以原本之CRUD公會之冒險者註冊為例,冒險者登記完資料後,AutoMapper可直接將資料映射至公會之表內,禮賓部不必進行二次填寫:
// 原禮賓部需二次填寫冒險者所寫資料
[HttpPost]
public async Task<IActionResult> Post(InformationDto Information)
{
AdventurerProfile profile = new AdventurerProfile()
{
Sigil = Guid.NewGuid().ToString(),
Name = Information.Name,
Race = Information.Race,
Class = Information.Class,
Dwelling = Information.Dwelling,
Created_At = DateTime.Now
};
_Context.AdventurersProfile.Add(profile);
try
{
await _Context.SaveChangesAsync();
}
catch (Exception ex)
{
return Ok("1");
}
return Ok(0);
}
// 利用AutoMapper後,禮賓部便可映射冒險者所填之資料至AdventurerPrfile中
[HttpPost]
public async Task<IActionResult> Post(InformationDto Information)
{
AdventurerProfile profile = new AdventurerProfile();
profile = _mapper.Map(Information, profile);
_Context.AdventurersProfile.Add(profile);
try
{
await _Context.SaveChangesAsync();
}
catch (Exception ex)
{
return Ok("1");
}
return Ok(new JsonResult (new { profile.Sigil }));
}