使用Mapper由非泛型转化为泛型
初始化
新建两个Model类
public class PageModel
{
public int Page { get; set; }
public int PageSize { get; set; }
public string Key { get; set; }
public PageModel()
{
Page = 1;
PageSize = 10;
}
}
public class PageOutModel<T>:PageModel
{
/// <summary>
/// 数量
/// </summary>
public int Count { get; set; }
/// <summary>
/// 数据内容
/// </summary>
public T Data { get; set; }
}
新建 MapperProfiles 继承 Profile
public class MapperProfiles : Profile
{
public MapperProfiles()
{
CreateMap(typeof(PageModel), typeof(PageOutModel<>));
}
}
使用
Startup.cs 中对Mapper进行注入
public class Startup
{
...
public IServiceProvider ConfigureServices(IServiceCollection services)
{
...
services.AddAutoMapper();
...
}
...
}
在要用的地方中用 构造函数注入,然后使用
public class TestService
{
private readonly IMapper _mapper;
public TestService(IMapper mapper)
{
_mapper = mapper;
}
public async Task<PageOutModel<IEnumerable<object>>> GetListAsync(PageModel model)
{
...
var data = _mapper.Map<PageModel, PageOutModel<IEnumerable<object>>>(model);
...
return data;
}
}
出现错误
报错:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
...
...
Unmapped properties:
Count
Data
解决方法
修改 Profile
添加 忽略属性 Ignore
public class MapperProfiles : Profile
{
public MapperProfiles()
{
CreateMap(typeof(PageModel), typeof(PageOutModel<>)).ForAllMembers(c=>c.Ignore());
}
}
完美解决问题