You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
2.0 KiB
60 lines
2.0 KiB
3 months ago
|
using AutoMapper;
|
||
|
using AutoMapper.Internal;
|
||
|
using System;
|
||
|
using System.Linq;
|
||
|
using System.Reflection;
|
||
|
|
||
|
namespace Kean.Application.Utilities
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 模型映射配置
|
||
|
/// </summary>
|
||
|
public class AutoMapper : Profile
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 初始化 Kean.Application.Utilities.AutoMapper 类的新实例
|
||
|
/// </summary>
|
||
|
public AutoMapper()
|
||
|
{
|
||
|
/* 这是一个例子:
|
||
|
* 只需在 ViewModels 文件夹下创建视图模型,配置与数据表实体的映射即可
|
||
|
* 注意:在最后 ReverseMap(),确保双向映射处理读写能力
|
||
|
*
|
||
|
* CreateMap<Test, T_TEST>()
|
||
|
* .ForMember(entity => entity.TEST_ID, options => options.MapFrom(viewmodel => viewmodel.Id))
|
||
|
* .ForMember(entity => entity.TEST_NAME, options => options.MapFrom(viewmodel => viewmodel.Name))
|
||
|
* .ReverseMap();
|
||
|
*/
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// AutoMapper 扩展方法
|
||
|
/// </summary>
|
||
|
internal static class AutoMapperExtension
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// 获取映射配置
|
||
|
/// </summary>
|
||
|
/// <param name="mapper">映射</param>
|
||
|
/// <param name="type">ViewModel 类型名</param>
|
||
|
/// <returns>映射配置</returns>
|
||
|
internal static TypeMap GetMap(this IMapper mapper, string type)
|
||
|
{
|
||
|
var assembly = Assembly.GetExecutingAssembly();
|
||
|
var viewModelType = assembly.GetType($"{assembly.FullName.Split(',')[0]}.ViewModels.{type}", false, true);
|
||
|
if (viewModelType == null)
|
||
|
{
|
||
|
throw new TypeLoadException("ViewModel 不存在。");
|
||
|
}
|
||
|
var map = mapper.ConfigurationProvider.Internal().GetAllTypeMaps()
|
||
|
.FirstOrDefault(m => m.SourceType == viewModelType);
|
||
|
if (map == null)
|
||
|
{
|
||
|
throw new AutoMapperMappingException("未配置 ViewModel 与 Entity 之间的映射。");
|
||
|
}
|
||
|
return map;
|
||
|
}
|
||
|
}
|
||
|
}
|