[C#.NET] 使用 AutoMapper.Profile 簡化對應設定
我們應該要把這些對應關係給集中管理,設定一次所有的開發人員都能夠用,AutoMapper 也有提供集中管理的機制,真是太棒了
很簡單,只要實作 AutoMapper.Profile 並覆寫 Configure 方法,把相關的對應關係擺好
@ AccountMapperProfile:
public class AccountMapperProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Account, AccountTwViewModel>()
.ForMember(target => target.帳號, option => option.MapFrom(source => source.UserId))
.ForMember(target => target.密碼, option => option.MapFrom(source => source.Password));
Mapper.CreateMap<AccountTwViewModel, Account>()
.ForMember(target => target.UserId, option => option.MapFrom(source => source.帳號))
.ForMember(target => target.Password,option => option.MapFrom(source => source.密碼));
}
}
@ 調用端:
1.用戶端調用 Mapper.Initialize 把映射關係加進去
Mapper.Initialize(x => x.AddProfile<AccountMapperProfile>());
2.再調用 Mapper.Map 方法,就可以產生新的物件
Mapper.Map<AccountTwViewModel>(account);
程式碼如下:
public class UnitTest3
{
[TestMethod]
public void AutoMapper_Account_AccountTwViewModel_Test()
{
Account account = new Account();
account.UserId = "yao123";
account.Password = "1234";
Mapper.Initialize(x => x.AddProfile<AccountMapperProfile>());
var actual = Mapper.Map<AccountTwViewModel>(account);
Assert.AreEqual(account.UserId, actual.帳號);
Assert.AreEqual(account.Password, actual.密碼);
}
}
完整程式碼路徑如下:
更多用法:
https://github.com/AutoMapper/AutoMapper/wiki/Configuration
文章出自:http://www.dotblogs.com.tw/yc421206/archive/2014/12/12/147619.aspx
範例專案:https://dotblogsamples.codeplex.com/SourceControl/latest#Simple.AutoMapViewModel/
運行測試:Ctrl + R,Ctrl + A
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET