2010-08-24 92 views
0

有没有什么方法可以使其工作?这里是我的问题的简化/做作的插图(请原谅我的罗嗦VB):具有基类枚举属性的自动映射器

域模型类

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 

视图模型类

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 

映射和测试代码

<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 

回答

0

而不是这样做,我会映射到ViewModel一侧的并行继承层次结构。创建一个SeatModel,StandardSeatModel和一个CustomSeatModel。然后,您可以使用Include()配置选项将Seat - > SeatModel映射配置与映射配置链接到StandardSeat - > StandardSeatModel,另一个。

这样,你不需要所有的忽略()和什么。如果您仍然想要将原始模型弄平,则仍然需要在Seat - > SeatModel部分中包含Include()配置。

+0

感谢您的回应,吉米。我用Include()试了一些东西来平坦化原始模型,但没有成功 - 子类属性被忽略。 感谢您对ViewModel上的并行继承的建议。 – pettys 2010-08-24 18:26:59