标签: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>();
标签:target static auto configure models from 解决 类库 ignore
原文地址:http://www.cnblogs.com/Tom-yi/p/7451849.html