Model與ViewModel的Property常常是有很多重複的
互相轉換卻有點麻煩
曾經還自己寫了轉換小功能
翻到以前寫的code覺得蠻有趣的
紀錄一下
在沒用AutoMapper曾經自己有點愚蠢的寫了一個轉換小功能
/// <summary>Model與ViewMode的資料轉換</summary>
/// <typeparam name="T">原始資料Model的Class</typeparam>
/// <typeparam name="U">轉出資料Model的Class</typeparam>
public class ConvertModel<T,U>
{
/// <summary>轉換時根據此Type的逐項attribute</summary>
public Type mType { get; set; }
/// <summary>將T Model轉成U Model</summary>
/// <param name="SourceModel">原始資料的Model</param>
/// <param name="ConvertToModel">轉出資料的Model</param>
/// <returns>轉出資料的Model</returns>
public U ConvertTo(T SourceModel,U ConvertToModel)
{
foreach (var mItem in mType.GetProperties())
{
string PropertyName = mItem.Name;
var SetValue = SourceModel.GetType().GetProperty(PropertyName).GetValue(SourceModel);
ConvertToModel.GetType().GetProperty(PropertyName).SetValue(ConvertToModel, SetValue);
}
return ConvertToModel;
}
}
需要轉換的時候就new出來使用
public ActionResult Index()
{
Drinks drinks = new Drinks() {
Id = 1,
DrinksName = "BlackTea",
Quantity = 6,
CreateDate = DateTime.Now.AddHours(-1)
};
DrinksView drinksView = new DrinksView()
{
Id = 1,
DrinksName = "BlackTea",
Quantity = 6,
Other ="NiceDrink"
};
#region Model轉ViewModel
var ConvertTool = new ConvertModel<AdMgmtView, AdMgmt>() { mType = _Model.GetType() };
drinksView = ConvertTool.ConvertTo(_AdMgmt, _Model);
#endregion
return View(drinksView);
}
後來發現有一個套件AutoMapper
public ActionResult Index()
{
Drinks drinks = new Drinks() {
Id = 1,
DrinksName = "BlackTea",
Quantity = 6,
CreateDate = DateTime.Now.AddHours(-1)
};
DrinksView drinksView = new DrinksView()
{
Id = 1,
DrinksName = "BlackTea",
Quantity = 6,
Other ="NiceDrink"
};
#region Model轉ViewModel
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Drinks, DrinksView>();
});
IMapper mapper = config.CreateMapper();
var viewModel = mapper.Map<Drinks, DrinksView>(drinks);
#endregion
#region View轉Model
var config2 = new MapperConfiguration(cfg => {
cfg.CreateMap<DrinksView, Drinks>().ForMember(x => x.CreateDate, opts => opts.MapFrom(x=>DateTime.Now));
});
IMapper mapper2 = config2.CreateMapper();
var viewModel2 = mapper2.Map<DrinksView, Drinks>(drinksView);
#endregion
return View();
}
在NuGet上安裝之後就可以輕鬆的互相轉換了~