tags:

views:

24

answers:

1

Is there any way to get this to work? Here's a simplified/contrived illustration of my issue (Pardon my wordy VB):

Domain Model Classes

 Public Class Car
  Public Property Id As Integer
  Public Property Seats As IEnumerable(Of Seat)
 End Class

 Public MustInherit Class Seat
 End Class

 Public Class StandardSeat
  Inherits Seat
  Public Property Manufacturer As String
 End Class

 Public Class CustomSeat
  Inherits Seat
  Public Property Installer As String
 End Class

View Model Classes

Public Class CarModel
  Public Property Id As String
  Public Property Seats As IEnumerable(Of SeatModel)
 End Class

 Public Class SeatModel
  Public Property Manufacturer As String
  Public Property Installer As String
 End Class

Mapping and Test Code

<Test()> Public Sub Test()
 Mapper.CreateMap(Of Car, CarModel)()
 Mapper.CreateMap(Of Seat, SeatModel)() _
  .ForMember("Manufacturer", Sub(cfg) cfg.Ignore()) _
  .ForMember("Installer", Sub(cfg) cfg.Ignore())

 Mapper.CreateMap(Of StandardSeat, SeatModel)() _
  .ForMember("Installer", Sub(cfg) cfg.Ignore())
 Mapper.CreateMap(Of CustomSeat, SeatModel)() _
  .ForMember("Manufacturer", Sub(cfg) cfg.Ignore())

 Mapper.AssertConfigurationIsValid()

 Dim car As New Car With {.Id = 4}
 car.Seats = New Seat() {
  New StandardSeat With {.Manufacturer = "Honda"},
  New CustomSeat With {.Installer = "Napa"}}

 Dim model = Mapper.Map(Of Car, CarModel)(car)
 model.Id.ShouldEqual("4")
 model.Seats.Count().ShouldEqual(2)
 ' These next two assertions fail.
 model.Seats.First().Manufacturer.ShouldEqual("Honda")
 model.Seats.Last().Installer.ShouldEqual("Napa")
End Sub
A: 

Instead of doing this, I'd map to a parallel inheritance hierarchy on the ViewModel side. Create a SeatModel, StandardSeatModel and a CustomSeatModel. You would then use the Include() configuration option to link the Seat -> SeatModel mapping configuration to the mapping configurations to StandardSeat -> StandardSeatModel and the other.

This way, you don't need all the Ignore() s and whatnot. If you still want to flatten your original model, you'll still need to include the Include() configuration on the Seat -> SeatModel piece.

Jimmy Bogard
Thanks for the response, Jimmy. I did try a few things with Include() to flatten the original model, but didn't have success with that -- the subclass properties were ignored.Thanks for the suggestion about the parallel inheritance on the ViewModel.
pettys

related questions