[AutoMapper]AutoMapper 方法的使用

 

一、CreateMap

1
CreateMap<TSource, TDestination>();

說明:
用來將 TSource 之欄位對應至 TDestination 欄位。


二、ForMember、MapFrom

1
2
CreateMap<TSource, TDestination>()
.ForMember(TDestination => TDestination.AccountName, s => s.MapFrom(TSource => TSource.AccountName))

說明:
針對特定 TDestination 欄位,由 TSource 裡之一對一關聯特定欄位對應。


三、MapFrom

1
2
3
4
5
6
7
8
9
10
11
12
CreateMap<TSource, TDestination>()
.ForMember(TDestination => TDestination.CarParts,
s => s.MapFrom(
(TSource, TDestination) =>
TSource.Cars.Select(x => new CarPartDto{
CarId = TSource.CarId,
CarPartId = x.CarPartId,
CarPartName = x.CarPartName,
Valid = 1
})
)
)


四、BeforeMap

1
2
CreateMap<TSource, TDestination>()
.BeforeMap((TSource, TDestination) => TDestination.Valid = 1);


五、AfterMap

1
2
CreateMap<TSource, TDestination>()
.AfterMap((TSource, TDestination) => TDestination.Valid = 1);


六、ConvertUsing 自定義類型轉換

1
2
3
4
5
CreateMap<Account, string>()
.ConvertUsing(TSource => TSource.Email);

cfg.CreateProjection<Source, Dest>()
.ConvertUsing(src => new Dest { Value = 10 });

說明:
所對應至 TDestination 欄位(string),直接拿 TSource 特定欄位對應。


七、ProjectTo

1
_mapper.ProjectTo<TDestination>(IQueryable).ToList();

說明:將 IQueryable 集合對應到 TDestination。


八、其他方法
1、忽略指定的欄位:.Ignore()

參考資料:
AutoMapper —— 類別轉換超省力
AutoMapper