2011-10-28 38 views
12

Tôi có 1 lớp mà tôi cần ánh xạ vào nhiều lớp, ví dụ:Bản đồ tự động vào lớp lồng nhau

Đây là nguồn gốc mà tôi đang lập bản đồ từ (model view):

public class UserBM 
{ 
    public int UserId { get; set; } 

    public string Address { get; set; } 
    public string Address2 { get; set; } 
    public string Address3 { get; set; } 
    public string State { get; set; } 

    public int CountryId { get; set; } 
    public string Country { get; set; } 
} 

Đây là cách lớp đích là (mô hình tên miền):

public abstract class User 
{ 
    public int UserId { get; set; } 

    public virtual Location Location { get; set; } 
    public virtual int? LocationId { get; set; } 
} 

public class Location 
{ 
    public int LocationId { get; set; } 

    public string Address { get; set; } 
    public string Address2 { get; set; } 
    public string Address3 { get; set; } 
    public string State { get; set; } 

    public virtual int CountryId { get; set; } 
    public virtual Country Country { get; set; } 

} 

Đây là cách automapper của tôi tạo bản đồ hiện tại:

Mapper.CreateMap<UserBM, User>(); 

Trả lời

22

Xác định hai ánh xạ, cả ánh xạ từ cùng một nguồn đến các đích khác nhau. Trong các bản đồ User, lập bản đồ Location sở hữu bằng tay sử dụng Mapper.Map<UserBM, Location>(...)

Mapper.CreateMap<UserBM, Location>(); 
Mapper.CreateMap<UserBM, User>() 
    .ForMember(dest => dest.Location, opt => 
     opt.MapFrom(src => Mapper.Map<UserBM, Location>(src)); 
+0

làm thế nào bạn có thể làm điều ngược lại? – xrklvs

+4

Có một chuỗi tương tự trên [SO] (http://stackoverflow.com/questions/5984640/automapper-class-and-nested-class-map-to-one-class), nơi tôi thích tốt hơn bit cuối cùng của ánh xạ : thay vì 'opt.MapFrom (src => Mapper.Map (src)', nó sử dụng 'opt => opt.MapFrom (src => src)' đơn giản hơn – superjos

Các vấn đề liên quan