Sử dụng AutoMapper với số lượng thuộc tính khác nhau giữa DTO class và Model class

Xin chào,
VD mình có class Model với 5 thuộc tính như sau :

public class Account {
   public string ID;
   public string name;
   public string email;
   public string password;
   public DateTime timeCreate;
}

và một class DTO với 3 thuộc tính như này để trả kết quả cho client hiển thị:

public class AccountDTO {
   public string name;
   public string usernameOrEmail;
   public DateTime timeCreate;
}

Cho mình hỏi vậy dùng AutoMapper như thế nào trong trường hợp này.
Cảm ơn các bạn :ok_man: :bowing_man:

10 Likes

Cậu thử dùng Custome value resolves xem.
Ví dụ (trong doc cũng có):

// Map between source and destination
public class Source
{
	public int Value1 { get; set; }
	public int Value2 { get; set; }
}

public class Destination
{
	public int Total { get; set; }
}

Cậu tạo CustomResolver implement IValueResolver interface

public class CustomResolver : IValueResolver<Source, Destination, int>
{
	public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
	{
        return source.Value1 + source.Value2;
	}
}

Đây là configuration:

var configuration = new MapperConfiguration(cfg =>
   cfg.CreateMap<Source, Destination>()
	 .ForMember(dest => dest.Total, opt => opt.MapFrom<CustomResolver>()));
configuration.AssertConfigurationIsValid();

var source = new Source
	{
		Value1 = 5,
		Value2 = 7
	};

var result = mapper.Map<Source, Destination>(source);

result.Total.ShouldEqual(12);
4 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?