(精华)2020年9月21日 ASP.NET Core AutoMapper的使用

没有AutoMapper需要一个一个赋值

public class Sample01
{
    public static void Run()
    {
        var result = GetStudents();

        var students = new List<StudentViewModel>();

        foreach (var item in result)
        {
            var student = new StudentViewModel
            {
                Id = item.Id,
                Age = item.Age,
                Name = item.Name,
                Gender = item.Gender
            };
            students.Add(student);
        }
        Print(students);
    }

    public static List<Student> GetStudents()
    {
        var context = new SampleContext();
        return context.Students;
    }

    public static void Print(IList<StudentViewModel> studentViewModels)
    {
        foreach (var student in studentViewModels)
        {
            Console.WriteLine($"Id={student.Id};Name={student.Name};");
        }
    }
}

AutoMapper配置映射

public class Sample02
    {
        public static void Run()
        {
            
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Student, StudentViewModel>());
            var mapper = config.CreateMapper();

            var result = GetStudents();
            var students = mapper.Map<List<StudentViewModel>>(result);
            Print(students);
        }

        public static List<Student> GetStudents()
        {
            var context = new SampleContext();
            return context.Students;
        }

        public static void Print(IList<StudentViewModel> studentViewModels)
        {
            foreach (var student in studentViewModels)
            {
                Console.WriteLine($"Id={student.Id};Name={student.Name};Age={student.Age};Gender={student.Gender}");
            }
        }
    }

AutoMapper 扁平化映射

public static void Run()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<User, UserViewModel>()
            .ForMember(
                model => model.City,
                expression => expression.MapFrom(user => user.Address.City))
            .ForMember(
                model => model.Country,
                expression => expression.MapFrom(user => user.Address.Country))
            .ForMember(
                model => model.State,
                expression => expression.MapFrom(user => user.Address.State));
    });
    var mapper = config.CreateMapper();

    var result = GetUsers();
    var users = mapper.Map<List<UserViewModel>>(result);
    Print(users);
}

public static List<User> GetUsers()
{
    var context = new SampleContext();
    return context.Users;
}

public static void Print(IList<UserViewModel> userViewModels)
{
    foreach (var user in userViewModels)
    {
        Console.WriteLine($"Id={user.Id};Name={user.Name};City={user.City}");
    }
}

Profile

public class StudentProfile : Profile
{
    public StudentProfile()
    {
        CreateMap<Student, StudentViewModel>();
    }
}
public class UserProfile : Profile
{
    public UserProfile()
    {
        CreateMap<User, UserViewModel>()
            .ForMember(
                model => model.City,
                expression => expression.MapFrom(user => user.Address.City))
            .ForMember(
                model => model.State,
                expression => expression.MapFrom(user => user.Address.State))
            .ForMember(
                model => model.Country,
                expression => expression.MapFrom(user => user.Address.Country));

    }
}
public class Sample04
{
    public static void Run()
    {
        
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<UserProfile>();
            cfg.AddProfile<StudentProfile>();
        });

        var mapper = config.CreateMapper();

        var result = GetUsers();
        var users = mapper.Map<List<UserViewModel>>(result);
        Print(users);
    }

    public static List<User> GetUsers()
    {
        var context = new SampleContext();
        return context.Users;
    }

    public static void Print(IList<UserViewModel> userViewModels)
    {
        foreach (var user in userViewModels)
        {
            Console.WriteLine($"Id={user.Id};Name={user.Name};City={user.City}");
        }
    }
}

AutoMapper 自定义解析

public class Customer
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}
public class CustomerViewModel
{
    public int Id { get; set; }

    public string FullName { get; set; }
}
public class CustomerResolver : IValueResolver<Customer, CustomerViewModel, string>
{
    public string Resolve(Customer source, CustomerViewModel destination, string destMember, ResolutionContext context)
    {
        return source.FirstName + " " + source.LastName;
    }
}
public static void Run()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Customer, CustomerViewModel>()
            .ForMember(model => model.FullName, expression => expression.MapFrom<CustomerResolver>());
    });

    var mapper = config.CreateMapper();

    var customer = new Customer
    {
        Id = 1,
        FirstName = "Klein",
        LastName = "Moretti"
    };

    var result = mapper.Map<CustomerViewModel>(customer);
    Console.WriteLine(result.FullName);
}

AutoMapper 自定义类型转换

public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
}
public class PersonViewModel
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Age { get; set; }
}
 public class StringTypeConverter : ITypeConverter<int, string>
{

    public string Convert(int source, string destination, ResolutionContext context)
    {
        return source.ToString();
    }
}
public static void Run()
{
    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<int, string>().ConvertUsing<StringTypeConverter>();
        cfg.CreateMap<Person, PersonViewModel>();
    });

    var mapper = config.CreateMapper();

    var person = new Person
    {
        Id = 1,
        Age = 10
    };

    var result = mapper.Map<PersonViewModel>(person);
    Console.WriteLine($"{result.Age.GetType()}:Age={result.Age})");
}

AutoMapper 动态对象映射

public static void Run()
{
    var config = new MapperConfiguration(cfg => {});
    var mapper = config.CreateMapper();

    var customer = new Customer
    {
        Id = 1,
        FirstName = "Klein",
        LastName = "Moretti"
    };

    // 强类型对象映射到动态类型对象
    var result = mapper.Map<dynamic>(customer);
    Console.WriteLine($"result:{result.FirstName} {result.LastName}");

    // 动态类型对象映射到强类型对象
    customer = mapper.Map<Customer>(result);
    Console.WriteLine($"customer:{customer.FirstName} {customer.LastName}");

    // 字典对象映射到强类型对象
    var dict = new Dictionary<string, object> {{"FirstName", "Klein"}, {"LastName", "Moretti"}};
    customer = mapper.Map<Customer>(dict);
    Console.WriteLine($"dictToCustomer:{customer.FirstName} {customer.LastName}");
}

AutoMapper在ASP.NET Core中使用

首先安装如下两个包

AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        services.AddSingleton<SampleContext>();
        services.AddScoped<OrderRepository>();

        services.AddAutoMapper(Assembly.GetExecutingAssembly());

        services.AddMediatR(Assembly.GetExecutingAssembly());
        
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
public class OrderProfile : Profile
    {
        public OrderProfile()
        {
            CreateMap<Order, GetOrderByIdResponseModel>();
        }
    }
public class GetOrderByIdResponseModel
    {
        public Guid Id { get; set; }
        public DateTime DateOrder { get; set; }
        public int Quantity { get; set; }
        public double Amount { get; set; }
        public Guid ProductId { get; set; }
        public string ProductName { get; set; }
    }
public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdRequestModel, GetOrderByIdResponseModel>
{
    private readonly OrderRepository _orderRepository;
    private readonly IMapper _mapper;

    public GetOrderByIdQueryHandler(OrderRepository orderRepository, IMapper mapper)
    {
        _orderRepository = orderRepository;
        _mapper = mapper;
    }

    public Task<GetOrderByIdResponseModel> Handle(GetOrderByIdRequestModel request, CancellationToken cancellationToken)
    {
        var order = _orderRepository.GetById(request.OrderId);
        var response = _mapper.Map<GetOrderByIdResponseModel>(order);
        return Task.FromResult(response);
    }
}
[Route("api/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
    private readonly IMediator _mediator;

    public OrderController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public IActionResult MakeOrder([FromBody] MakeOrderRequestModel requestModel)
    {
        var response = _mediator.Send(requestModel).Result;
        return Ok(response);
    }

    [HttpGet("{id}")]
    public IActionResult OrderDetails(Guid id)
    {
        var response = _mediator.Send(new GetOrderByIdRequestModel {OrderId = id}).Result;
        return Ok(response);
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页