標籤:target static auto configure models from 解決 類庫 ignore
第一、建立類庫,以解決方案名XXX為例,建立子類庫名為 XXX.AutoMapper。
第二、 XXX.AutoMapper類庫中,添加對automap的引用。
第三、建立對應檔類 ModelProfile,繼承Profile
codes:
---------------------------------------------
namespace BCMS.AutoMapper.Profiles
{
public class ModelProfile : Profile
{
public ModelProfile()
{
//配置相關映射
//eg
CreateMap<BaseUserEntity, BaseUserModel>()
.ForMember(model => model.StaffName, entity => entity.Ignore())
.ForMember(model => model.StaffNo, entity => entity.Ignore())
.ForMember(model => model.LocationTypeName, entity => entity.Ignore())
.ForMember(model => model.IsADLoginName, entity => entity.Ignore())
.ForMember(model => model.TypeName, entity => entity.Ignore())
.ForMember(model => model.BaseUserRoles, (map) => map.MapFrom(m => m.BaseUserRoles));
CreateMap<BaseUserModel, BaseUserEntity>()
.ForMember(model => model.BaseUserRoles, (map) => map.MapFrom(m => m.BaseUserRoles));
//................................
}}}//end
-----------------------------------------------------------------------------
第四、在類庫名為 XXX.AutoMapper的類庫中建立Configuration類(如果有就不用建立)把映射類ModelProfile 配置進去。
codes:
----------------------------------------------------------------
namespace BCMS.AutoMapper
{
public class Configuration
{
public static void Configure()
{
Mapper.Initialize(cfg => { cfg.AddProfile<ModelProfile>(); });//增加對 ModelProfile的初始化
Mapper.AssertConfigurationIsValid();
}
}
}
---------------------------------------------------------------------
第五、應用 automap。
把原生的automap進行擴充,封裝。
建立一個XXX.Util類庫,添加對 XXX.AutoMapper的引用。
建立靜態擴充類,public static class AutoMapperExtensions
codes:
-------------------------------
public static class AutoMapperExtensions
{
public static T ToModel<T>(this object entity)
{
return Mapper.Map<T>(entity);
}
public static T ToEntity<T>(this object viewModel)
{
if (viewModel == null)
return default(T);
return Mapper.Map<T>(viewModel);
}
public static IEnumerable<T> ToModelList<T>(this IEnumerable entityList)
{
if (entityList == null)
return null;
return (from object entity in entityList select entity.ToModel<T>()).ToList();
}
}
-------------------------------------------------
在Service層使用的時候,添加對XXX.Util類庫的引用就可以了。
使用eg:
1.Model=>Entity
ProductModel editViewModel =new ProductModel (){Name ="AAAA"};
var entity = editViewModel.ToEntity<ProductEntity>();//轉換為Entity
2.集合間轉換。
IEnumerable<TargetMarketEntity> entitys = _targetMarketRepository.GetList(new { LocationTypeId = LocationTypeId });
IEnumerable<TargetMarketModel> models =entitys .ToModelList<TargetMarketModel>();
asp.netMVC中配置automap