wpf prism 中使用automapper

时间:2024-03-10 08:47:32

1.首先引入包Automapper。
在App.xmal.cs中添加注入

protected override IContainerExtension CreateContainerExtension()
{
    var serviceCollection = new ServiceCollection();
    serviceCollection.AddAutoMapper();
    return new DryIocContainerExtension(new Container(CreateContainerRules())
        .WithDependencyInjectionAdapter(serviceCollection));
}

AutoMapperExtension类

public static class AutoMapperExtension
{
    public static void AddAutoMapper(this IServiceCollection services)
    {
        if (services == null) throw new ArgumentNullException(nameof(services));

        services.AddAutoMapper(typeof(AutoMapperConfig));
        AutoMapperConfig.RegisterMappings();
    }
}

AutoMapperConfig类:

 public class AutoMapperConfig
 {
     /// <summary>
     /// 注册实体类之间的映射关系
     /// </summary>
     /// <returns></returns>
     public static MapperConfiguration RegisterMappings()
     {
         return new MapperConfiguration(cfg =>
         {
             cfg.AddProfile(new AutoMapperProfile());
         });
     }
 }

AutoMapperProfile类:

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile() 
    {
        CreateMap<User, UserModel>();
    }
}

使用实例:

private IMapper _mapper;
private SqlSugarClient _db;

public UserService(SqlSugarClient db, IMapper mapper)
{
    _db = db;
    _mapper = mapper;
}

public List<UserModel> GetUsers()
{
    var users = _db.Queryable<User>().ToList();
    var result = _mapper.Map<List<User>,List<UserModel>>(users);
    return result;
}