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>();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM