AutoMapper集成
包管理器添加
AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection
创建AutoMapper文件夹,在文件夹中创建AutoMapperConfig.cs类(也可以不创建文件夹,重要是为了代码简洁,方便观看)
/// <summary> /// 静态全局 AutoMapper 配置文件 /// </summary> public class AutoMapperConfig { public static MapperConfiguration RegisterMappings() { return new MapperConfiguration(cfg => { cfg.AddProfile(new CustomProfile()); }); } }
上面 CustomProfile 还没有创建
按AIt+Enter在新文件中生成CustomProfile或者在AutoMapper 文件夹中创建CustomProfile,继承Profile
public class CustomProfile : Profile { /// <summary> /// 配置构造函数,用来创建关系映射 /// </summary> public CustomProfile() { //第一个参数是原对象,第二个是目的对象 CreateMap<Person, PersonViewModel>(); } }
Person和PersonViewModel 下面有
使用 在Controller中 依赖注入
private readonly IMapper _mapper; public WeatherForecastController( IMapper mapper) { _mapper = mapper; }
用于演示的两个类
一般在开发中AutoMapper使用的场景都是实体类和ViewModel的转换
public class Person { public Guid Id { get; set; } public string Name { get; set; } public string height { get; set; } public string wieght { get; set; } public string Education { get; set; } }
public class PersonViewModel { public Guid Id { get; set; } public string Name { get; set; } public string Education { get; set; } }
使用
Person person = new Person() { Id = Guid.NewGuid(), Name="张翼德", height="八尺", wieght="五百斤", Education="文盲" }; PersonViewModel model = _mapper.Map<PersonViewModel>(person);
一定要在CustomProfile类中配置,否侧会报错
AutoMapper.AutoMapperMappingException:“Missing type map configuration or unsupported mapping.”
缺少类型映射配置或不支持的映射