Tôi vừa làm việc này và có giải pháp tuyệt vời. Rất có thể là hai quan điểm của bạn thực sự liên quan đến một cách nào đó trong hệ thống của bạn (đặc biệt là nếu bạn đang sử dụng Khung thực thể). Kiểm tra các mô hình của bạn và bạn sẽ thấy một cái gì đó hiển thị các mối quan hệ, nếu bạn không sau đó chỉ cần thêm nó. (Các virtual
)
mô hình của bạn
public class Dto1
{
public int id { get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
public string Property4 { get; set; }
public string Property5 { get; set; }
public virtual Dto2 dto2{ get; set; }
}
public class Dto2
{
public int id { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
public string PropertyD { get; set; }
public string PropertyE { get; set; }
}
ViewModels của bạn
public class Dto1ViewModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public virtual Dto2VMForDto1 dto2{ get; set; }
}
//Special ViewModel just for sliding into the above
public class Dto2VMForDto1
{
public int id { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
}
Automapper trông như thế này:
cfg.CreateMap< Dto1, Dto1ViewModel>();
cfg.CreateMap< Dto2, Dto2VMForDto1 >();
tôi giả sử bạn đang nhận được dữ liệu của bạn với LINQ:
Dto1ViewModel thePageVM = (from entry in context.Dto1 where...).ProjectTo<Dto1ViewModel>();
Viola, mọi thứ sẽ hoạt động. Trong chế độ xem của bạn, chỉ cần truy cập bằng cách sử dụng model.dto2.PropertyB
bạn có thể sử dụng ValueInjecter http://valueinjecter.codeplex.com/documentation – Omu