NEWS

[C#] Giới thiệu và sử dụng thư viện AutoMapper

[C#] Giới thiệu và sử dụng thư viện AutoMapper
Đăng bởi: Thảo Meo - Lượt xem: 3701 11:26:20, 12/08/2022DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình giới thiệu và hướng dẫn các bạn sử dụng thư viện AutoMapper dùng để ánh xạ dữ liệu giữa 2 class với nhau.

Vậy tại sao chúng ta cần sử dụng AutoMapper.

[C#] AutoMapper in C# with Example

auto_mapper_lib

Các bạn thấy thư viện, đang có 289 triệu lượt tải, một thư viện rất phổ biến. Khi các bạn làm việc với Entity Framework

VD: Các bạn có 2 class như hình ảnh bên dưới

auto_mapper_employee

và ví dụ: bạn có dữ liệu trong class Employee như bên dưới

emp.Name = "James";
emp.Salary = 20000;
emp.Address = "London";
emp.Department = "IT";

và bây giờ bạn muốn copy tất cả dữ liệu đó qua EmployeeDTO, các bạn sẽ thực hiện như sau:

namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Name = "James";
            emp.Salary = 20000;
            emp.Address = "London";
            emp.Department = "IT";
            EmployeeDTO empDTO = new EmployeeDTO();
            empDTO.Name = emp.Name;
            empDTO.Salary = emp.Salary;
            empDTO.Address = emp.Address;
            empDTO.Department = emp.Department;
            Console.WriteLine("Name:" + empDTO.Name + ", Salary:" + empDTO.Salary + ", Address:" + empDTO.Address + ", Department:"+ empDTO.Department);
            Console.ReadLine();
        }
    }
    
    public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
    
    public class EmployeeDTO
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}

Thay vì công việc chúng ta phải làm thủ công như vậy, thì thư viện AutoMapper sẽ giúp bạn 

Đầu tiên, các bạn cài đặt thư viện AutoMapper từ Nuget

PM> Install-Package AutoMapper -Version 11.0.1

và bây giờ các bạn chỉ cần config để ánh xạ 2 class Employee và EmployeeDTO

var config = new MapperConfiguration(cfg =>
    cfg.CreateMap<Employee, EmployeeDTO>()
);

Full đoạn code bạn sử dụng AutoMapper:

using System;
using AutoMapper;
namespace AutoMapperDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize the mapper
            var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Employee, EmployeeDTO>()
                );
            //Creating the source object
            Employee emp = new Employee
            {
                Name = "James",
                Salary = 20000,
                Address = "London",
                Department = "IT"
            };
            //Using automapper
            var mapper = new Mapper(config);
            var empDTO = mapper.Map<EmployeeDTO>(emp);
            //OR
            //var empDTO2 = mapper.Map<Employee, EmployeeDTO>(emp);
            Console.WriteLine("Name:" + empDTO.Name + ", Salary:" + empDTO.Salary + ", Address:" + empDTO.Address + ", Department:" + empDTO.Department);
            Console.ReadLine();
        }
    }
    
    public class Employee
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
    public class EmployeeDTO
    {
        public string Name { get; set; }
        public int Salary { get; set; }
        public string Address { get; set; }
        public string Department { get; set; }
    }
}

Nhưng đó là trường hợp 2 cột tên của 2 class đều giống nhau,

nhưng bây giờ, nếu 2 cột tên khác nhau như: 

Class Employee thuộc tính là "name" còn EmployeeDTO là "fullname" chẳng hạn, thì ở config cấu hình các bạn cần chỉ rõ cho nó biết là field nào ánh xạ với filed nào

 var config = new MapperConfiguration(cfg =>
                    cfg.CreateMap<Employee, EmployeeDTO>()
                    .ForMember(dest => dest.FullName, act => act.MapFrom(src => src.Name))
                    .ForMember(dest => dest.Dept, act => act.MapFrom(src => src.Department))
);

Thanks for watching!

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Giới thiệu và sử dụng thư viện AutoMapper
Đăng bởi: Thảo Meo - Lượt xem: 3701 11:26:20, 12/08/2022DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.