asp.netMVC中配置automap

第一、新建类库,以解决方案名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>();

 

转载于:https://www.cnblogs.com/Tom-yi/p/7451849.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值